diff --git a/core/engine/src/compiled/core/exec.rs b/core/engine/src/compiled/core/exec.rs index d134526f..15285884 100644 --- a/core/engine/src/compiled/core/exec.rs +++ b/core/engine/src/compiled/core/exec.rs @@ -1,8 +1,10 @@ use super::list::Frame; +use super::switch::{Cost, Path}; use crate::compiled::leaf::{Bits, Leaf}; -use crate::compiled::shred::Listing; +use crate::compiled::shred::{Coder, Listing}; use std::rc::Rc; -use std::sync::atomic::{AtomicU32, Ordering}; +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}; @@ -22,8 +24,29 @@ pub(crate) struct TypedCall<'l, 'a> { 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, } impl TypedCall<'_, '_> { @@ -59,9 +82,136 @@ impl Select { 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 { sparse: AtomicU32::new(0) } + Self { + 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 = Instant::now(); + if out.is_some() && coded(cx).is_none() { + self.coded.store(Self::FAILED, Ordering::Relaxed); + } + (out, choice(Rows::Warm, begin.elapsed())) + } + Rows::Probe => { + let begin = Instant::now(); + let out = plain(cx); + if out.is_some() { + self.part.store(Self::per(begin.elapsed(), local), Ordering::Relaxed); + self.pending.store(true, Ordering::Relaxed); + } + (out, choice(Rows::Probe, Duration::ZERO)) + } + } + } + + pub fn settle(&self, cost: &Cost, path: (Path, bool), 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 = Instant::now(); + let tried = coded(cx).is_some(); + let part = Self::per(begin.elapsed(), 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 { @@ -242,3 +392,79 @@ impl Dedup { Some((codes.into(), count)) } } + +#[cfg(test)] +mod tests { + use super::{Choice, Dedup}; + use crate::compiled::core::switch::{Cost, Path}; + use std::time::{Duration, Instant}; + + struct Spin; + + impl Spin { + fn run(micros: u64) -> Option { + let until = Instant::now() + Duration::from_micros(micros); + while Instant::now() < until { + std::hint::spin_loop(); + } + Some(micros) + } + + fn call(dedup: &Dedup, cost: &Cost, plain: u64, coded: u64, merged: u64) -> Option { + let start = Instant::now(); + let (out, choice): (Option, Choice) = dedup.choose(&mut (), 1024, |_| Self::run(plain), |_| Self::run(coded)); + Self::run(merged); + dedup.settle(cost, (Path::Typed, false), choice, start.elapsed(), 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::new(), 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::new(), Cost::new()); + let mut runs: Vec> = (0..2).map(|_| Spin::call(&dedup, &cost, 400, 50, 20)).collect(); + let start = Instant::now(); + let (out, choice) = dedup.choose(&mut (), 1024, |_| Spin::run(400), |_| Spin::run(50)); + Spin::run(900); + dedup.settle(&cost, (Path::Typed, false), choice, start.elapsed(), 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::new(), 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::new(), 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, (Path::Typed, 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/switch.rs b/core/engine/src/compiled/core/switch.rs index bdc9644c..5ab60ff4 100644 --- a/core/engine/src/compiled/core/switch.rs +++ b/core/engine/src/compiled/core/switch.rs @@ -52,6 +52,16 @@ impl Cost { } } + 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, (path, fresh): (Path, bool), 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 { diff --git a/core/engine/src/compiled/graph/plan/run/store.rs b/core/engine/src/compiled/graph/plan/run/store.rs index 071a2efb..23f98a92 100644 --- a/core/engine/src/compiled/graph/plan/run/store.rs +++ b/core/engine/src/compiled/graph/plan/run/store.rs @@ -6,6 +6,7 @@ use crate::compiled::graph::plan::{SegPlan, Source}; use zen_expression::typed::Outputs; use crate::nodes::NodeError; use crate::compiled::shred::{Listing, Normalizer}; +use crate::compiled::core::exec::{Dedup, Hint}; use crate::compiled::leaf::{Bits, Dict, Leaf, Records}; use crate::EvaluationError; use std::rc::Rc; @@ -70,6 +71,7 @@ pub(crate) struct Store<'a> { 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), @@ -127,6 +129,7 @@ impl<'a> Store<'a> { 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), @@ -150,6 +153,7 @@ impl<'a> Store<'a> { }; 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)); } @@ -293,6 +297,15 @@ impl<'a> Store<'a> { 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 { .. }); diff --git a/core/engine/src/compiled/graph/plan/run/typed.rs b/core/engine/src/compiled/graph/plan/run/typed.rs index 0eab3a0d..dbaadbca 100644 --- a/core/engine/src/compiled/graph/plan/run/typed.rs +++ b/core/engine/src/compiled/graph/plan/run/typed.rs @@ -1,11 +1,12 @@ use crate::compiled::graph::plan::view::{M, SlotId}; use crate::compiled::graph::table::{First, Table}; -use crate::compiled::core::exec::{Hint, ListPart, Select, TypedCall}; +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::{Op, SegPlan, TableOp}; -use zen_expression::typed::{Data as Slotted, Slot}; +use zen_expression::lane::Values; +use zen_expression::typed::{Data as Slotted, Outputs, Slot}; use crate::compiled::shred::{Normalizer, Seen}; use crate::compiled::leaf::{Bits, Leaf}; use crate::compiled::graph::{Body, Kind}; @@ -14,6 +15,8 @@ use std::time::Instant; use super::Run; use super::store::{Lowered, Prepared, Store}; +type Held<'a> = (Choice, Vec>, 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; @@ -68,14 +71,17 @@ impl<'a> Run<'_, 'a> { } let path = op.cost.path(); let start = Instant::now(); + let mut held: Held<'a> = (Choice::default(), Vec::new(), Vec::new()); let typed = match path.0 { - Path::Typed => self.lowered(seg, op, positions).map(|lowered| self.merged(seg, op, units, positions, lowered)).is_some(), + 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 { self.laned(seg, units, positions); } - op.cost.record(path, start.elapsed(), local); + let (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)); } fn laned(&mut self, seg: &SegPlan, units: &[Op], positions: Option<&Rc<[usize]>>) { @@ -230,7 +236,7 @@ impl<'a> Run<'_, 'a> { } } - fn lowered(&mut self, seg: &SegPlan, op: &TypedOp, positions: Option<&Rc<[usize]>>) -> Option { + 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 @@ -238,7 +244,8 @@ impl<'a> Run<'_, 'a> { .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 keyed = op.dedup.ready() && op.lists.is_empty() && op.dedup.eligible(&op.program, &raw, &hints); + 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() { @@ -263,36 +270,67 @@ impl<'a> Run<'_, 'a> { } None => { let select: Option> = positions.map(|positions| Select::bits(rows, positions)); - 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: select.as_deref(), + 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 = (choice, leaves, hints); + out? + } + false => (self.plain(seg, op, &leaves, select.as_deref())?, None), }; - let out = call.run(&op.program)?; - Some((out, None, select, prefault)) + let select = match ids { + Some(_) => None, + None => select, + }; + Some((out, 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/policy/columnar/typed.rs b/core/engine/src/compiled/policy/columnar/typed.rs index 1ac962aa..35e551c3 100644 --- a/core/engine/src/compiled/policy/columnar/typed.rs +++ b/core/engine/src/compiled/policy/columnar/typed.rs @@ -3,7 +3,7 @@ use crate::compiled::core::fuse::Fused; use super::{Bind, Member, Pass, Sheet}; use crate::compiled::core::switch::{Cost, Density, Path}; use crate::compiled::core::variants::Variants; -use crate::compiled::core::exec::{ListPart, Select, TypedCall}; +use crate::compiled::core::exec::{Choice, Dedup, Hint, ListPart, Select, TypedCall}; use crate::compiled::core::group::{Built, Prefix, Step}; use crate::compiled::core::list::Frame; use crate::compiled::core::retry::Take; @@ -14,6 +14,7 @@ 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 { @@ -21,6 +22,7 @@ pub(crate) struct TypedGroup { sinks: Vec, pub(super) units: usize, pub(super) cost: Cost, + dedup: Dedup, probe: Box<[Probed]>, columns: Vec, lists: Vec>, @@ -147,6 +149,7 @@ impl TypedGroup { sinks: Vec::new(), units: 0, cost: Cost::new(), + dedup: Dedup::new(), probe: record.into(), columns: Vec::new(), lists: Vec::new(), @@ -184,6 +187,7 @@ impl TypedGroup { sinks, units, cost: Cost::new(), + dedup: Dedup::new(), probe: record.into(), columns, lists, @@ -257,9 +261,18 @@ impl<'s, 'a> Pass<'s, 'a> { if path.0 == Path::Lane { return Typed::Lane(group, path); } - let (start, count) = (Instant::now(), rows.len()); + let (start, count, asked, whole) = (Instant::now(), rows.len(), rows, full); let select = (!full).then(|| Select::bits(total, rows)); - let Some(mut out) = self.execute(&group, program, &sources, entity, select.as_deref()) else { + 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 { return Typed::Skipped; }; let (faulted, kept) = match out.faults().any() { @@ -271,7 +284,8 @@ impl<'s, 'a> Pass<'s, 'a> { false => kept.as_slice(), }; if rows.is_empty() { - group.cost.record(path, start.elapsed(), count); + 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; @@ -299,10 +313,35 @@ impl<'s, 'a> Pass<'s, 'a> { self.sink(&group.sinks, leaves, Some((at, &kids)), rows); } } - group.cost.record(path, start.elapsed(), count); + 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)? { diff --git a/core/engine/src/compiled/shred.rs b/core/engine/src/compiled/shred.rs index 9220b04a..f2562dd5 100644 --- a/core/engine/src/compiled/shred.rs +++ b/core/engine/src/compiled/shred.rs @@ -23,7 +23,7 @@ pub(crate) enum Seen { Mixed, } -struct Coder<'d> { +pub(crate) struct Coder<'d> { data: &'d [u8], slots: [u8; Coder::SLOTS], entries: Vec<((u64, u64, usize), usize)>, @@ -411,7 +411,7 @@ impl<'d> Coder<'d> { (hash >> 57) as usize } - fn codes(mut self, offsets: &[i32]) -> Option<(Vec, Dict)> { + 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 { @@ -419,6 +419,17 @@ impl<'d> Coder<'d> { } 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); diff --git a/core/engine/tests/compiled.rs b/core/engine/tests/compiled.rs index c6976c98..716d2461 100644 --- a/core/engine/tests/compiled.rs +++ b/core/engine/tests/compiled.rs @@ -571,12 +571,15 @@ async fn columnar_graph_throughput() { continue; } let mut best = [f64::MAX; 2]; - for _ in 0..5 { - let start = std::time::Instant::now(); - for c in contexts.iter().take(256) { - let _ = walker.evaluate(c.clone()).await; + 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); } - 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 { diff --git a/core/engine/tests/compiled.rs.orig b/core/engine/tests/compiled.rs.orig new file mode 100644 index 00000000..c6976c98 --- /dev/null +++ b/core/engine/tests/compiled.rs.orig @@ -0,0 +1,1402 @@ +mod support; +#[path = "support/fixture.rs"] +mod fixture; + +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()) { + 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()) { + 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]; + for _ in 0..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() { + 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 _ = Decision::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 Decision::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 { + std::env::var("ZEN_TYPED").map_or(true, |v| v.trim() != "0") + } + + fn graph(nodes: Vec) -> GraphContent { + 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.typed, output.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 mut 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/expression/src/typed/output.rs b/core/expression/src/typed/output.rs index da0a69fa..9321f83a 100644 --- a/core/expression/src/typed/output.rs +++ b/core/expression/src/typed/output.rs @@ -166,6 +166,53 @@ impl Slot { } } + fn spread(&mut self, sources: &[u32]) { + let rows = sources.len(); + let pick = |id: u32| (id != u32::MAX).then_some(id as usize); + let mut valid = vec![0u64; K::words(rows)]; + for (row, &id) in sources.iter().enumerate() { + if pick(id).is_some_and(|at| K::get(&self.valid, at)) { + K::set(&mut valid, row, true); + } + } + self.data = match std::mem::replace(&mut self.data, Data::Bool(Vec::new())) { + Data::Num { mant, scale } => Data::Num { + mant: sources.iter().map(|&id| pick(id).and_then(|at| mant.get(at).copied()).unwrap_or(0)).collect(), + scale: sources.iter().map(|&id| pick(id).and_then(|at| scale.get(at).copied()).unwrap_or(0)).collect(), + }, + Data::Bool(bits) => { + let mut out = vec![0u64; K::words(rows)]; + for (row, &id) in sources.iter().enumerate() { + if pick(id).is_some_and(|at| K::get(&bits, at)) { + K::set(&mut out, row, true); + } + } + Data::Bool(out) + } + Data::Code(codes) => Data::Code(sources.iter().map(|&id| pick(id).and_then(|at| codes.get(at).copied()).unwrap_or(0)).collect()), + Data::Text { span, data } => Data::Text { + span: sources.iter().map(|&id| pick(id).and_then(|at| span.get(at).copied()).unwrap_or((0, 0))).collect(), + data, + }, + Data::Date(dates) => Data::Date(sources.iter().map(|&id| pick(id).and_then(|at| dates.get(at).copied().flatten())).collect()), + }; + if !self.wide.is_empty() { + let wide = std::mem::take(&mut self.wide); + self.wide = sources + .iter() + .enumerate() + .filter_map(|(row, &id)| { + let at = pick(id)?; + let found = wide.binary_search_by_key(&at, |(at, _)| *at).ok()?; + wide.get(found).map(|(_, d)| (row, *d)) + }) + .collect(); + } + self.valid = valid; + self.fault = self.fault.spread(sources); + self.len = rows; + } + fn reset(&mut self, len: usize) { self.len = len; self.wide.clear(); @@ -206,6 +253,20 @@ impl Slot { } impl Faults { + fn spread(&self, sources: &[u32]) -> Self { + let mut bits = vec![0u64; K::words(sources.len())]; + let mut any = false; + if self.any { + for (row, &id) in sources.iter().enumerate() { + if id != u32::MAX && K::get(&self.bits, id as usize) { + K::set(&mut bits, row, true); + any = true; + } + } + } + Self { bits, rows: sources.len(), any } + } + pub(crate) fn reset(&mut self, rows: usize) { self.bits.clear(); self.bits.resize(K::words(rows), 0); @@ -313,6 +374,29 @@ impl Outputs { &self.faults } + pub fn spread(&mut self, rows: usize, ids: &[u32], positions: Option<&[usize]>) -> bool { + let reps = self.rows; + if self.slots.iter().any(|slot| slot.offsets.is_some() || slot.len != reps) || positions.is_some_and(|p| p.len() != ids.len()) { + return false; + } + let mut sources = match positions { + None => ids.to_vec(), + Some(_) => vec![u32::MAX; rows], + }; + if let Some(positions) = positions { + positions.iter().zip(ids).for_each(|(&row, &id)| sources[row] = id); + } + if sources.len() != rows || sources.iter().any(|&id| id != u32::MAX && id as usize >= reps) { + return false; + } + self.rows = rows; + self.faults = self.faults.spread(&sources); + for slot in &mut self.slots { + slot.spread(&sources); + } + true + } + pub(crate) fn parts(&mut self) -> (&mut [Slot], &mut Faults) { (&mut self.slots, &mut self.faults) } @@ -386,3 +470,77 @@ impl Slot { self.offsets = Some(out); } } + +#[cfg(test)] +mod tests { + use super::{Data, Faults, Outputs, Slot}; + use crate::typed::hir::{Kind, Scope}; + use crate::typed::kernel::K; + use rust_decimal::Decimal; + + struct Build; + + impl Build { + fn slot(kind: Kind, data: Data, valid: &[bool], faulted: &[usize], wide: Vec<(usize, Decimal)>) -> Slot { + let mut bits = vec![0u64; K::words(valid.len())]; + valid.iter().enumerate().for_each(|(at, &on)| K::set(&mut bits, at, on)); + let mut fault = Faults::default(); + fault.reset(valid.len()); + faulted.iter().for_each(|&at| fault.set(at)); + Slot { + name: String::new(), + scope: Scope::Row, + kind, + len: valid.len(), + data, + valid: bits, + fault, + wide, + offsets: None, + keep: Vec::new(), + } + } + + fn reps() -> Outputs { + let num = Self::slot(Kind::Num(None), Data::Num { mant: vec![15, 7, 0], scale: vec![1, 0, 0] }, &[true, true, false], &[2], vec![(1, Decimal::MAX)]); + let text = Self::slot(Kind::Text, Data::Text { span: vec![(0, 2), (2, 5), (5, 5)], data: b"abxyz".to_vec() }, &[true, true, false], &[], Vec::new()); + let flag = Self::slot(Kind::Bool, Data::Bool(vec![0b101]), &[true, false, true], &[], Vec::new()); + let mut faults = Faults::default(); + faults.reset(3); + faults.set(2); + Outputs { rows: 3, slots: vec![num, text, flag], faults } + } + } + + #[test] + fn spread_maps_every_row_to_its_representative() { + let mut out = Build::reps(); + assert!(out.spread(5, &[1, 0, 2, 1, 0], None)); + assert_eq!(out.rows(), 5); + let num = &out.slots()[0]; + assert_eq!((0..5).map(|at| num.decimal(at)).collect::>(), vec![Some(Decimal::MAX), Some(Decimal::new(15, 1)), None, Some(Decimal::MAX), Some(Decimal::new(15, 1))]); + assert_eq!(num.fault.iter().collect::>(), vec![2]); + assert_eq!(out.faults().iter().collect::>(), vec![2]); + let text = &out.slots()[1]; + assert_eq!((0..5).map(|at| text.text(at)).collect::>(), vec![Some("xyz"), Some("ab"), None, Some("xyz"), Some("ab")]); + let flag = &out.slots()[2]; + assert_eq!((0..5).map(|at| flag.boolean(at)).collect::>(), vec![None, Some(true), Some(true), None, Some(true)]); + } + + #[test] + fn spread_leaves_unselected_rows_invalid_and_unfaulted() { + let mut out = Build::reps(); + assert!(out.spread(6, &[2, 0, 1], Some(&[1, 3, 4]))); + let num = &out.slots()[0]; + assert_eq!((0..6).map(|at| num.is_valid(at)).collect::>(), vec![false, false, false, true, true, false]); + assert_eq!(num.fault.iter().collect::>(), vec![1]); + assert_eq!(num.wide, vec![(4, Decimal::MAX)]); + } + + #[test] + fn spread_rejects_mismatched_ids() { + let mut out = Build::reps(); + assert!(!out.spread(2, &[0, 3], None)); + assert!(!out.spread(4, &[0, 1], Some(&[0]))); + } +}