diff --git a/core/engine/src/compiled/policy/columnar/evaluate.rs b/core/engine/src/compiled/policy/columnar/evaluate.rs index d3dd9d9e..ea9b3026 100644 --- a/core/engine/src/compiled/policy/columnar/evaluate.rs +++ b/core/engine/src/compiled/policy/columnar/evaluate.rs @@ -442,6 +442,7 @@ impl PolicyPlan { delegated: false, counts: Paths::default(), listed: RefCell::new(Vec::new()), + casts: RefCell::new(Vec::new()), present: self.gates.iter().map(|_| OnceCell::new()).collect(), owners: self.flats() .map(|plan| plan.iteration.as_ref().map(|(_, path, _)| path.clone())) diff --git a/core/engine/src/compiled/policy/columnar/fuse.rs b/core/engine/src/compiled/policy/columnar/fuse.rs index eb6251ae..b95c51fa 100644 --- a/core/engine/src/compiled/policy/columnar/fuse.rs +++ b/core/engine/src/compiled/policy/columnar/fuse.rs @@ -3,12 +3,14 @@ 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::leaf::{Array, Bits, Dict, Leaf, Literal, Store}; use crate::compiled::lowered::Exports; use crate::compiled::policy::blocks::Operator; use crate::compiled::policy::schedule::{End, Event, Segment}; use crate::compiled::policy::{Native, PolicyPlan}; -use crate::compiled::table::TableIr; +use crate::compiled::shred::Normalizer; +use crate::compiled::table::Picked; +use crate::compiled::table::{Table, TableIr}; use crate::policy::blocks::{AssertionIr, BlockKind, DecisionTableIr, MatchIr}; use std::cmp::Ordering; use std::rc::Rc; @@ -16,6 +18,7 @@ use std::sync::{Arc, RwLock}; use std::time::Instant; use zen_expression::lane::{Fusion, LaneProgram}; use zen_expression::typed::TableSpec; +use zen_expression::Variable; use zen_types::path::DotPath; type Groups = ahash::HashMap>>; @@ -25,7 +28,7 @@ type Lanes = ahash::HashMap, Option>>>; pub(crate) struct Fusions { groups: RwLock, effects: RwLock>>>, - tables: RwLock>, + tables: RwLock>>, runs: Runs, pub(super) typed: RwLock, } @@ -67,6 +70,154 @@ struct Item { pub(super) enum Sink { Write(Arc), Assert(Arc), + Gather(Gather), +} + +pub(super) enum Cell { + Constant(Literal), + Computed, +} + +pub(super) struct Gather { + fields: Vec>, + scalars: Vec, + rules: Vec>, + computed: usize, +} + +impl Gather { + pub fn of(ir: &DecisionTableIr, table: &Table) -> Self { + let profile = TableIr::policy(ir); + let picked = table.picked(); + let mut fields: Vec> = Vec::new(); + let mut scalars: Vec = Vec::new(); + let targets: Vec = profile + .written() + .map(|o| match fields.iter().position(|f| f.as_ref() == o.path) { + Some(at) => at, + None => { + fields.push(Arc::from(o.path)); + scalars.push(!o.collect); + fields.len() - 1 + } + }) + .collect(); + let mut computed = 0; + let rules = profile + .rules + .iter() + .enumerate() + .map(|(at, rule)| { + profile + .written() + .enumerate() + .filter(|(_, o)| profile.cell(rule, o.id).is_some()) + .map(|(column, _)| { + let constant = Self::literal(picked, at, column); + let cell = match constant { + Some(value) => Cell::Constant(value), + None => { + computed += 1; + Cell::Computed + } + }; + (targets[column], cell) + }) + .collect() + }) + .collect(); + Self { + fields, + scalars, + rules, + computed, + } + } + + pub fn literal(picked: &[Picked], rule: usize, column: usize) -> Option { + picked.get(column)?.constants.get(rule)?.clone() + } + + fn leaves<'a>(&self, conds: &[Vec], values: &[Leaf<'a>], count: usize) -> Vec> { + let mut masks = vec![0u64; count]; + for (rule, bits) in conds.iter().enumerate() { + for row in Bits::rows(bits) { + if let Some(mask) = masks.get_mut(row) { + *mask |= 1 << rule; + } + } + } + let gather = |mask: u64, row: usize| -> Vec> { + let mut lists = vec![Vec::new(); self.fields.len()]; + let mut next = 0; + for (rule, cells) in self.rules.iter().enumerate() { + let matched = mask & (1 << rule) != 0; + for (target, cell) in cells { + let taken = matched && !(self.scalars[*target] && !lists[*target].is_empty()); + match cell { + Cell::Constant(value) if taken => lists[*target].push(value.variable()), + Cell::Constant(_) => {} + Cell::Computed => { + if taken { + lists[*target].push(values.get(next).map_or(Variable::Null, |leaf| leaf.get(row))); + } + next += 1; + } + } + } + } + lists + }; + let value = |scalar: bool, list: Vec| match scalar { + true => list.into_iter().next().unwrap_or(Variable::Null), + false => Variable::from_array(list), + }; + let typed = |column: Vec| { + let leaf = Leaf::Any(column.into()); + Normalizer::cast(&leaf).unwrap_or(leaf) + }; + if self.computed > 0 { + let mut columns: Vec> = vec![Vec::with_capacity(count); self.fields.len()]; + for (row, mask) in masks.iter().enumerate() { + for ((column, list), scalar) in columns.iter_mut().zip(gather(*mask, row)).zip(&self.scalars) { + column.push(value(*scalar, list)); + } + } + return columns + .into_iter() + .zip(&self.scalars) + .map(|(column, scalar)| match scalar { + true => typed(column), + false => Leaf::Any(column.into()), + }) + .collect(); + } + let mut seen: ahash::HashMap = ahash::HashMap::default(); + let mut distinct: Vec = Vec::new(); + let codes: Rc<[i32]> = masks + .iter() + .map(|mask| { + *seen.entry(*mask).or_insert_with(|| { + distinct.push(*mask); + distinct.len() as i32 - 1 + }) + }) + .collect(); + let mut dicts: Vec> = vec![Vec::with_capacity(distinct.len()); self.fields.len()]; + for mask in &distinct { + for ((dict, list), scalar) in dicts.iter_mut().zip(gather(*mask, 0)).zip(&self.scalars) { + dict.push(value(*scalar, list)); + } + } + dicts + .into_iter() + .zip(&self.scalars) + .map(|(values, scalar)| match scalar { + true => typed(codes.iter().map(|&code| values[code as usize].clone()).collect()), + false => Leaf::typed(Array::coded(codes.clone(), Rc::new(Dict::Any(values)))), + }) + .collect() + } } struct Unit<'p> { @@ -76,7 +227,7 @@ struct Unit<'p> { } impl Fusions { - fn table(&self, block: usize, ir: &DecisionTableIr) -> bool { + fn table(&self, block: usize, ir: &DecisionTableIr) -> Option { if let Some(found) = self .tables .read() @@ -85,11 +236,16 @@ impl Fusions { { return found; } - let typable = TableIr::policy(ir).typable(); + let profile = TableIr::policy(ir); + let found = match (profile.typable(), profile.gathers()) { + (true, _) => Some(true), + (false, true) => Some(false), + (false, false) => None, + }; if let Ok(mut cache) = self.tables.write() { - cache.insert(block, typable); + cache.insert(block, found); } - typable + found } fn effects(&self, plan: &PolicyPlan, block: usize) -> Option> { @@ -725,13 +881,15 @@ impl<'s, 'a> Pass<'s, 'a> { if !self.quiet(block) { return Err("table cells read fields"); } - if !plan.fusions.table(block, ir) { - return Err("table not typable"); - } + let readable = match plan.fusions.table(block, ir) { + Some(false) if !Exports::enabled() => return Err("table not typable"), + Some(readable) => readable, + None => return Err("table not typable"), + }; let writes: Vec<(Arc, bool)> = table .picked() .iter() - .map(|o| (o.field.clone(), true)) + .map(|o| (o.field.clone(), readable)) .collect(); (entity, table.programs(), writes) } @@ -827,7 +985,23 @@ impl<'s, 'a> Pass<'s, 'a> { let count = member.map_or(rows.len(), |(_, kids)| kids.len()); let mut leaves = leaves.into_iter(); for sink in sinks { + if let Sink::Gather(gather) = sink { + let conds: Vec> = leaves + .by_ref() + .take(gather.rules.len()) + .map(|leaf| leaf.truths(count)) + .collect(); + let values: Vec> = leaves.by_ref().take(gather.computed).collect(); + for (key, leaf) in gather.fields.iter().zip(gather.leaves(&conds, &values, count)) { + match member { + None => self.write(key, leaf, rows), + Some((at, kids)) => self.member_write(at, key, leaf, kids), + } + } + continue; + } let leaf = match sink { + Sink::Gather(_) => continue, 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); @@ -851,6 +1025,7 @@ impl<'s, 'a> Pass<'s, 'a> { let key = match sink { Sink::Write(key) => key, Sink::Assert(ir) => &ir.output, + Sink::Gather(_) => continue, }; match member { None => self.write(key, leaf, rows), diff --git a/core/engine/src/compiled/policy/columnar/host.rs b/core/engine/src/compiled/policy/columnar/host.rs index 333d2c37..9f273287 100644 --- a/core/engine/src/compiled/policy/columnar/host.rs +++ b/core/engine/src/compiled/policy/columnar/host.rs @@ -124,12 +124,19 @@ impl<'s, 'a> Pass<'s, 'a> { } pub(super) fn quiet(&self, block: usize) -> bool { - self.artifact - .read_plans - .get(&self.plan.blocks.refs[block]) - .is_none_or(|plan| { - crate::compiled::policy::schedule::Blocks::idle(self.artifact, &plan.conditional) - }) + let quiet = self.plan.quiet.get_or_init(|| { + self.plan + .blocks + .refs + .iter() + .map(|owner| { + self.artifact.read_plans.get(owner).is_none_or(|plan| { + crate::compiled::policy::schedule::Blocks::idle(self.artifact, owner, plan) + }) + }) + .collect() + }); + quiet.get(block).copied().unwrap_or(false) } pub(super) fn hosted(&self, block: usize, row: usize) -> bool { diff --git a/core/engine/src/compiled/policy/columnar/mod.rs b/core/engine/src/compiled/policy/columnar/mod.rs index 5294d89f..ec5b43d4 100644 --- a/core/engine/src/compiled/policy/columnar/mod.rs +++ b/core/engine/src/compiled/policy/columnar/mod.rs @@ -69,6 +69,7 @@ struct Pass<'s, 'a> { delegated: bool, counts: Paths, listed: RefCell>>, + casts: RefCell>)>>, present: Vec>>>, } diff --git a/core/engine/src/compiled/policy/columnar/typed.rs b/core/engine/src/compiled/policy/columnar/typed.rs index b1bcc561..4b68b6a2 100644 --- a/core/engine/src/compiled/policy/columnar/typed.rs +++ b/core/engine/src/compiled/policy/columnar/typed.rs @@ -1,4 +1,4 @@ -use super::fuse::{Chain, Fusions, Sink, Span}; +use super::fuse::{Chain, Fusions, Gather, Sink, Span}; use super::{Bind, Listed, Member, Pass, Sheet}; use crate::compiled::census::Census; use crate::compiled::core::exec::{Dedup, Hint, ListPart, Part as Key, Select, TypedCall}; @@ -11,6 +11,7 @@ use crate::compiled::core::variants::Variants; use crate::compiled::leaf::Leaf; use crate::compiled::lowered::Exports; use crate::compiled::shred::{Listing, Normalizer}; +use crate::compiled::table::TableIr; use crate::policy::blocks::BlockKind; use std::rc::Rc; use std::sync::Arc; @@ -52,6 +53,8 @@ enum Source<'a> { List(usize, Vec), Listed(usize), Spread(Rc>), + CastEntry(usize), + CastField(usize), Absent, } @@ -129,14 +132,24 @@ impl TypedGroup { return Step::Stop; } let lowered = match &pass.plan.rule(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) - }), + BlockKind::DecisionTable(ir) => match Fused::::spec(ir) { + Some(spec) => { + let sunk: Vec = spec + .outputs + .iter() + .map(|key| Sink::Write(Arc::from(key.as_str()))) + .collect(); + Some((lowering.table(&spec, probe), sunk)) + } + None => pass.plan.flat(block).table.as_ref().and_then(|table| { + let picked = table.picked(); + let spec = TableIr::policy(ir).gathered(|rule, column| { + Gather::literal(picked, rule, column).is_none() + })?; + let sunk = vec![Sink::Gather(Gather::of(ir, table))]; + Some((lowering.table(&spec, probe), sunk)) + }), + }, _ => Fused::::entries(pass.plan, block, entity.is_some()) .map(|(entries, sunk)| (lowering.unit(&entries, probe), sunk)), }; @@ -509,9 +522,12 @@ impl<'s, 'a> Pass<'s, 'a> { ) -> Option { let leaf = |at: usize| -> Option> { match sources.get(at)? { - Source::Entry(_) | Source::Raw(_) => self.entry_leaf(sources.get(at)?), + Source::Entry(_) | Source::Raw(_) | Source::CastEntry(_) => { + self.entry_leaf(sources.get(at)?) + } Source::Field(field) => Some(self.sheet.entities[entity?].view(*field)), Source::RawField(field) => self.sheet.entities[entity?].raw_view(*field), + Source::CastField(field) => Normalizer::cast(&self.sheet.entities[entity?].view(*field)), Source::List(..) | Source::Listed(_) | Source::Spread(_) | Source::Absent => None, } }; @@ -623,17 +639,31 @@ impl<'s, 'a> Pass<'s, 'a> { match source { Source::Entry(entry) => Some(self.sheet.entries[*entry].leaf.clone()), Source::Raw(entry) => self.sheet.entries[*entry].declared(), + Source::CastEntry(entry) => self.cast(*entry), _ => None, } } + fn cast(&self, entry: usize) -> Option> { + if let Some((_, leaf)) = self.casts.borrow().iter().find(|(at, _)| *at == entry) { + return leaf.clone(); + } + let leaf = Normalizer::cast(&self.sheet.entries[entry].leaf); + self.casts.borrow_mut().push((entry, leaf.clone())); + leaf + } + fn bound(&self, entry: usize) -> (Resolved, Source<'a>) { if self.sheet.entries[entry].declared().is_some() { return (Resolved::Dated, Source::Raw(entry)); } - match Normalizer::of(&self.sheet.entries[entry].leaf) { + let leaf = &self.sheet.entries[entry].leaf; + match Normalizer::of(leaf) { Some(class) => (Resolved::Column(class), Source::Entry(entry)), - None => self.listed_entry(entry), + None => match Normalizer::castable(leaf) { + Some(class) => (Resolved::Column(class), Source::CastEntry(entry)), + None => self.listed_entry(entry), + }, } } @@ -834,10 +864,6 @@ impl<'s, 'a> Pass<'s, 'a> { ask: Ask, ) -> (Resolved, Source<'a>) { let unsupported = (Resolved::Unsupported, Source::Absent); - let column = |leaf: &Leaf, source: Source<'a>| match Normalizer::of(leaf) { - Some(class) => (Resolved::Column(class), source), - None => (Resolved::Unsupported, Source::Absent), - }; match (entity, ask) { (_, Ask::Nested) => { let chain: Vec<&str> = key.split('\n').collect(); @@ -852,7 +878,16 @@ impl<'s, 'a> Pass<'s, 'a> { Member::Field(field) if owner.fields[field].leaf.declared().is_some() => { (Resolved::Dated, Source::RawField(field)) } - Member::Field(field) => column(&owner.view(field), Source::Field(field)), + Member::Field(field) => { + let view = owner.view(field); + match Normalizer::of(&view) { + Some(class) => (Resolved::Column(class), Source::Field(field)), + None => match Normalizer::castable(&view) { + Some(class) => (Resolved::Column(class), Source::CastField(field)), + None => unsupported, + }, + } + } Member::Absent => (Resolved::Absent, Source::Absent), _ => unsupported, } diff --git a/core/engine/src/compiled/policy/mod.rs b/core/engine/src/compiled/policy/mod.rs index 07e89c4f..b66aeecf 100644 --- a/core/engine/src/compiled/policy/mod.rs +++ b/core/engine/src/compiled/policy/mod.rs @@ -193,6 +193,7 @@ pub(crate) struct PolicyPlan { root: Arc, special: std::sync::RwLock>>, safe: std::sync::OnceLock>, + quiet: std::sync::OnceLock>, fusions: columnar::Fusions, programs: Arc, rooted: Vec>, @@ -296,6 +297,7 @@ impl PolicyPlan { root, special: std::sync::RwLock::new(Specialized::new(Self::SPECIAL)), safe: std::sync::OnceLock::new(), + quiet: std::sync::OnceLock::new(), fusions: columnar::Fusions::default(), programs: artifact.programs(), } diff --git a/core/engine/src/compiled/policy/schedule.rs b/core/engine/src/compiled/policy/schedule.rs index 1ba792de..439faff5 100644 --- a/core/engine/src/compiled/policy/schedule.rs +++ b/core/engine/src/compiled/policy/schedule.rs @@ -1,6 +1,6 @@ use crate::compiled::core::segments::Children; use crate::compiled::policy::artifact::Artifact as EvalArtifact; -use crate::policy::blocks::{Block, BlockKind, ConditionalReads}; +use crate::policy::blocks::{Block, BlockKind, BlockReadPlan, ConditionalReads}; use crate::workspace::types::BlockRef; use ahash::{HashMap, HashSet}; use std::sync::Arc; @@ -60,13 +60,19 @@ impl Blocks { Self { refs, rules, index } } - pub(crate) fn idle(artifact: &EvalArtifact, reads: &ConditionalReads) -> bool { - let quiet = |paths: &[Arc]| { - paths - .iter() - .all(|path| artifact.writers_of_longest_prefix(path).is_empty()) + pub(crate) fn idle(artifact: &EvalArtifact, owner: &BlockRef, plan: &BlockReadPlan) -> bool { + let mut demanded: Option> = None; + let mut quiet = |paths: &[Arc]| { + paths.iter().all(|path| { + let writers = artifact.writers_of_longest_prefix(path); + if writers.is_empty() { + return true; + } + let before = demanded.get_or_insert_with(|| Self::demanded(artifact, plan)); + !before.contains(&owner) && writers.iter().all(|writer| before.contains(&writer)) + }) }; - match reads { + match &plan.conditional { ConditionalReads::None => true, ConditionalReads::Match(arms) => arms.iter().all(|arm| quiet(&arm.value_reads)), ConditionalReads::DecisionTable(cells) => { @@ -75,6 +81,23 @@ impl Blocks { } } + fn demanded<'a>(artifact: &'a EvalArtifact, plan: &'a BlockReadPlan) -> Vec<&'a BlockRef> { + let mut seen: Vec<&BlockRef> = Vec::new(); + let mut paths: Vec<&Arc> = plan.unconditional.iter().collect(); + while let Some(path) = paths.pop() { + for writer in artifact.writers_of_longest_prefix(path) { + if seen.contains(&writer) { + continue; + } + seen.push(writer); + if let Some(next) = artifact.read_plans.get(writer) { + paths.extend(next.unconditional.iter()); + } + } + } + seen + } + pub(crate) fn selects(rule: &Block) -> bool { matches!(rule.kind, BlockKind::Match(_) | BlockKind::DecisionTable(_)) } @@ -127,7 +150,7 @@ impl Sim<'_> { let rule = &self.blocks.rules[block]; if Blocks::selects(rule) { self.events.push(Event::Select(block)); - let conditional = plan.is_some_and(|p| !Blocks::idle(self.artifact, &p.conditional)); + let conditional = plan.is_some_and(|p| !Blocks::idle(self.artifact, owner, p)); if conditional { let Some(demand) = self.script.get(self.used) else { self.stopped = Some(block); diff --git a/core/engine/src/compiled/policy/validator.rs b/core/engine/src/compiled/policy/validator.rs index a3bf3d88..f3f91af4 100644 --- a/core/engine/src/compiled/policy/validator.rs +++ b/core/engine/src/compiled/policy/validator.rs @@ -741,9 +741,13 @@ impl Sureness<'_> { Self::boolean(column) || matches!(column.variable(at), Variable::Bool(_) | Variable::Null) } - PropertyTypeIr::Enum(values) if Self::string(column) => column - .text(at) - .is_none_or(|text| values.iter().any(|v| v.as_ref() == text)), + PropertyTypeIr::Enum(values) if Self::string(column) => { + column.bytes(at).is_some_and(|bytes| { + values.iter().any(|v| v.as_bytes() == bytes) + }) || column + .text(at) + .is_none_or(|text| values.iter().any(|v| v.as_ref() == text)) + } PropertyTypeIr::Enum(values) => match column.variable(at) { Variable::Null => true, Variable::String(s) => values.iter().any(|v| v.as_ref() == s.as_str()), @@ -783,6 +787,22 @@ impl Sureness<'_> { } fn loose_items(&self, prop: &Property, value: &Variable) -> bool { + let primitive = |item: &Variable| match (&prop.kind, item) { + (_, Variable::Null) => Some(true), + (PropertyTypeIr::String, item) => Some(matches!(item, Variable::String(_))), + (PropertyTypeIr::Number, item) => Some(matches!(item, Variable::Number(_))), + (PropertyTypeIr::Boolean, item) => Some(matches!(item, Variable::Bool(_))), + _ => None, + }; + if let Variable::Array(items) = value { + if let Some(all) = items + .borrow() + .iter() + .try_fold(true, |all, item| primitive(item).map(|ok| all && ok)) + { + return all; + } + } match value { Variable::Null => return true, Variable::Array(items) @@ -792,6 +812,25 @@ impl Sureness<'_> { .all(|item| Self::shallow(item, MAX_RECURSION_DEPTH / 2)) => {} _ => return false, } + if let Variable::Array(items) = value { + let mut known = Some(true); + for item in items.borrow().iter() { + if matches!(item, Variable::Null) { + continue; + } + match self.fits(&prop.kind, item, 0) { + Some(true) => {} + Some(false) => return false, + None => { + known = None; + break; + } + } + } + if let Some(all) = known { + return all; + } + } if matches!(prop.kind, PropertyTypeIr::Reference { .. }) { return false; } @@ -809,6 +848,80 @@ impl Sureness<'_> { validator.errors.is_empty() } + fn date_fits(&self, text: &str) -> bool { + let mut seen = self.dates.borrow_mut(); + if let Some(known) = seen.get(text) { + return *known; + } + let known = zen_expression::DateValue::is_text(text); + if seen.len() < InputValidator::REMEMBERED { + seen.insert(Box::from(text), known); + } + known + } + + fn fits(&self, kind: &PropertyTypeIr, value: &Variable, depth: usize) -> Option { + let named = |known: &dyn Fn(&str) -> bool| value.as_rc_str().is_some_and(|text| known(&text)); + Some(match kind { + PropertyTypeIr::String => matches!(value, Variable::String(_)), + PropertyTypeIr::Number => matches!(value, Variable::Number(_)), + PropertyTypeIr::Boolean => matches!(value, Variable::Bool(_)), + PropertyTypeIr::Enum(values) => named(&|text| values.iter().any(|v| v.as_ref() == text)), + PropertyTypeIr::Date => match value { + Variable::String(text) => text.is_empty() || self.date_fits(text), + other => zen_expression::DateValue::is(other), + }, + PropertyTypeIr::Reference { .. } => return None, + PropertyTypeIr::Relationship { target } => { + match (self.schema.entities.contains_key(target), self.schema.dictionaries.get(target)) { + (false, Some(dict)) => named(&|text| dict.values().any(|v| v.as_ref() == text)), + _ => self.entity_fits(target, value, depth)?, + } + } + }) + } + + fn entity_fits(&self, target: &str, value: &Variable, depth: usize) -> Option { + if depth >= MAX_RECURSION_DEPTH { + return Some(false); + } + let Some(object) = value.as_object() else { + return Some(false); + }; + let Some(model) = self.schema.entities.get(target) else { + return Some(true); + }; + for (key, value) in object.borrow().iter() { + if matches!(value, Variable::Null) { + continue; + } + let Some(prop) = model.properties.iter().find(|p| *p.name == *key.as_str()) else { + continue; + }; + let fits = match (prop.array, value.as_array()) { + (false, _) => self.fits(&prop.kind, value, depth + 1)?, + (true, None) => false, + (true, Some(items)) => { + let mut all = true; + for item in items.borrow().iter() { + if matches!(item, Variable::Null) { + continue; + } + if !self.fits(&prop.kind, item, depth + 1)? { + all = false; + break; + } + } + all + } + }; + if !fits { + return Some(false); + } + } + Some(true) + } + fn shallow(value: &Variable, limit: usize) -> bool { if limit == 0 { return false; @@ -847,6 +960,9 @@ impl Sureness<'_> { Variable::Object(_) if nesting(value, 0) <= SHALLOW => {} _ => return false, } + if let Some(fits) = self.entity_fits(target, value, 0) { + return fits; + } let pools = RefPoolIndex::from_input(&Variable::Null, std::iter::empty()); let mut validator = InputValidator { entities: &self.schema.entities, diff --git a/core/engine/src/compiled/shred.rs b/core/engine/src/compiled/shred.rs index f3a88248..ef03e623 100644 --- a/core/engine/src/compiled/shred.rs +++ b/core/engine/src/compiled/shred.rs @@ -1561,10 +1561,68 @@ impl<'a> Listing<'a> { }) } + fn coded(column: &Column<'_>, keys: &[i32], values: &[Variable], owners: usize) -> Option> { + let distinct = Self::shredded(&Column::new(Values::Any(values)), values.len())?; + let mut offsets: Vec = Vec::with_capacity(owners + 1); + offsets.push(0); + let mut valid = Bits::ones(owners); + let mut nulls = false; + let mut hosted: Option> = None; + let mut picks: Vec = Vec::new(); + for row in 0..owners { + let code = keys.get(row).and_then(|key| usize::try_from(*key).ok()); + match code.filter(|_| column.valid(row)) { + Some(code) => { + if distinct.hosted.as_ref().is_some_and(|bits| Bits::get(bits, code)) { + Bits::set(hosted.get_or_insert_with(|| vec![0u64; owners.div_ceil(64)]), row, true); + } + match distinct.frame.range(code) { + Some((a, b)) => picks.extend(a..b), + None => { + Bits::set(&mut valid, row, false); + nulls = true; + } + } + } + None => { + Bits::set(&mut valid, row, false); + nulls = true; + } + } + offsets.push(i32::try_from(picks.len()).ok()?); + } + let total = picks.len(); + let picks: Rc<[usize]> = picks.into(); + Some(Listing { + frame: Frame { + offsets: offsets.into(), + validity: nulls.then(|| valid.into()), + children: total, + }, + hosted: hosted.map(Rc::from), + fields: distinct + .fields + .iter() + .map(|(name, leaf)| (name.clone(), leaf.pick(&picks))) + .collect(), + dated: distinct + .dated + .iter() + .map(|(name, leaf)| (name.clone(), leaf.pick(&picks))) + .collect(), + }) + } + 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::Dict { + keys, + values: Dictionary::Any(values), + } if values.len() * 2 <= owners && keys.len() >= owners => { + Self::coded(column, keys, values, owners) + } Values::Any(_) | Values::Dict { values: Dictionary::Any(_), @@ -1659,41 +1717,35 @@ impl<'a> Listing<'a> { .collect() } - fn items<'v>( - column: &Column<'v>, + fn items( + column: &Column<'_>, row: usize, - ) -> Option>> { + visit: impl FnOnce(Option<&[Variable]>) -> R, + ) -> Option { if !column.valid(row) { - return Some(None); + return Some(visit(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, - }, + let value = match column.values { + Values::Any(values) => values.get(row)?, 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))), + } => { + let (a, b) = column.range(row)?; + return Some(visit(Some(items.get(a..b)?))); + } Values::Dict { keys, values: Dictionary::Any(values), } => match usize::try_from(*keys.get(row)?) { - Err(_) => Some(None), - Ok(key) => match values.get(key)? { - Variable::Null => Some(None), - Variable::Array(items) => { - Some(Some(std::borrow::Cow::Owned(items.borrow().clone()))) - } - _ => None, - }, + Err(_) => return Some(visit(None)), + Ok(key) => values.get(key)?, }, + _ => return None, + }; + match value { + Variable::Null => Some(visit(None)), + Variable::Array(items) => Some(visit(Some(&items.borrow()))), _ => None, } } @@ -1743,18 +1795,20 @@ impl<'a> Listing<'a> { } }; 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(_))); - } + Self::items(column, row, |items| { + if let Some(items) = items { + 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() { + Self::items(column, row, |items| { + for item in items.into_iter().flatten() { match (objects, item) { (true, Variable::Object(map)) => map .borrow() @@ -1764,7 +1818,7 @@ impl<'a> Listing<'a> { (false, item) => count("", item), } } - } + }); } let sorts: Vec<(Arc, usize)> = counts .into_iter() @@ -1786,11 +1840,19 @@ impl<'a> Listing<'a> { .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), + let placed = Self::items(column, row, |items| match items { + Some(items) if Self::odd(items, objects, &sorts) => false, + Some(items) => { + builder.row(row, items); + true + } + None => { + Bits::set(&mut builder.validity, row, false); + true + } + }); + if placed != Some(true) { + builder.host(row); } builder.close()?; } @@ -1837,6 +1899,83 @@ impl Normalizer { } } + fn scalars<'l>(leaf: &'l Leaf) -> Option<(Column<'l>, &'l [Variable])> { + if !matches!(leaf, Leaf::Any(_) | Leaf::Typed(_) | Leaf::Input(_)) { + return None; + } + let column = leaf.column(); + match column.values { + Values::Any(values) => Some((column, values)), + _ => None, + } + } + + pub(crate) fn castable(leaf: &Leaf) -> Option { + let (_, values) = Self::scalars(leaf)?; + let first = values.iter().find(|value| !matches!(value, Variable::Null))?; + let fits = |value: &Variable| match (first, value) { + (_, Variable::Null) => true, + (Variable::Bool(_), Variable::Bool(_)) | (Variable::String(_), Variable::String(_)) => true, + (Variable::Number(_), Variable::Number(n)) => Scaled::parts(n).is_some(), + _ => false, + }; + let class = match first { + Variable::Bool(_) => Class::Bool, + Variable::Number(_) => Class::Num, + Variable::String(_) => Class::Text, + _ => return None, + }; + values.iter().all(fits).then_some(class) + } + + pub(crate) fn cast<'a>(leaf: &Leaf<'a>) -> Option> { + let class = Self::castable(leaf)?; + let (column, values) = Self::scalars(leaf)?; + let rows = values.len(); + let mut valid = vec![0u64; rows.div_ceil(64)]; + for (at, value) in values.iter().enumerate() { + if !matches!(value, Variable::Null) && column.valid(at) { + Bits::set(&mut valid, at, true); + } + } + let store = match class { + Class::Bool => { + let mut bits = vec![0u64; rows.div_ceil(64)]; + for (at, value) in values.iter().enumerate() { + if let Variable::Bool(on) = value { + Bits::set(&mut bits, at, *on); + } + } + Store::Bool(bits) + } + Class::Num => { + let (mut mant, mut scale) = (Vec::with_capacity(rows), Vec::with_capacity(rows)); + for value in values { + let (m, e) = match value { + Variable::Number(n) => Scaled::parts(n)?, + _ => (0, 0), + }; + mant.push(m); + scale.push(e); + } + Store::Scaled { mant, scale } + } + _ => { + let mut offsets = Vec::with_capacity(rows + 1); + let mut data = String::new(); + offsets.push(0); + for value in values { + if let Variable::String(text) = value { + data.push_str(text); + } + offsets.push(i32::try_from(data.len()).ok()?); + } + Store::Text { offsets, data } + } + }; + Some(Leaf::typed(Array::parts(store, Some(valid), rows))) + } + pub(crate) fn class(values: &Values) -> Option { match values { Values::Scaled { .. } | Values::I64(_) | Values::Dec(_) => Some(Class::Num), diff --git a/core/engine/src/compiled/table/profile.rs b/core/engine/src/compiled/table/profile.rs index bb38b9b3..1a5da5c9 100644 --- a/core/engine/src/compiled/table/profile.rs +++ b/core/engine/src/compiled/table/profile.rs @@ -205,6 +205,54 @@ impl<'t> TableIr<'t> { }) } + pub fn gathers(&self) -> bool { + self.profile.strict() + && self.rules.len() <= Self::FILLED + && self.written().any(|o| o.collect) + && self.written().all(|o| { + self.written() + .all(|other| other.path != o.path || other.collect == o.collect) + }) + && self.inputs.iter().all(|input| { + input.field.is_some_and(|f| !f.trim().is_empty()) || !self.used(input.id) + }) + } + + pub fn gathered(&self, computed: impl Fn(usize, usize) -> bool) -> Option { + if !self.gathers() { + return None; + } + let inputs: Vec<&InputIr> = self.inputs.iter().filter(|input| self.used(input.id)).collect(); + let rules = self + .rules + .iter() + .enumerate() + .map(|(at, rule)| TableRule { + cells: inputs + .iter() + .map(|input| self.cell(rule, input.id).map(str::to_string)) + .collect(), + values: self + .written() + .enumerate() + .map(|(column, o)| { + self.cell(rule, o.id) + .filter(|_| computed(at, column)) + .map(str::to_string) + }) + .collect(), + }) + .collect(); + Some(TableSpec { + inputs: inputs.iter().map(|input| input.field.map(str::to_string)).collect(), + outputs: Vec::new(), + rules, + hit: Typed::Strict, + selector: false, + collect: true, + }) + } + pub fn spec(&self) -> Option { if self.collect || self.written().any(|o| o.collect) { return None; diff --git a/core/engine/tests/date_kernels.rs b/core/engine/tests/date_kernels.rs index b47b400f..f575741c 100644 --- a/core/engine/tests/date_kernels.rs +++ b/core/engine/tests/date_kernels.rs @@ -46,6 +46,8 @@ fn policy() -> String { add(format!("c.a.startOf('{unit}').diff(c.b.endOf('{unit}'), 'minute')")); add(format!("c.a.add(3, '{unit}').diff(c.a.sub(1, '{unit}'), 'hour')")); } + add("d().add(-24, 'hour').diff(c.a, 'minute')".into()); + add("c.a.add(1, 'day').diff(c.b, 'hour')".into()); add("c.a.diff(c.b)".into()); add("c.a.diff(c.n)".into()); for method in ["isSame", "isBefore", "isAfter", "isSameOrBefore", "isSameOrAfter"] { @@ -96,6 +98,7 @@ fn dates() -> Vec<&'static str> { "2025-03-19", "2025-03-20", "2025-03-20T10:15:30Z", + "2025-03-20T11:15:30+01:00", "2025-03-21T23:59:59", "2025-03-20T23:30:00-05:00", "2025-03-21T04:30:00+05:30", @@ -121,7 +124,7 @@ fn rows() -> Vec { } } let distinct = rows.len(); - (0..distinct * 24).map(|at| rows[at % distinct].clone()).collect() + (0..distinct * 24).map(|at| rows[(at / 3) % distinct].clone()).collect() } #[test] diff --git a/core/engine/tests/policy_parity.rs b/core/engine/tests/policy_parity.rs index f3a26250..566d0b21 100644 --- a/core/engine/tests/policy_parity.rs +++ b/core/engine/tests/policy_parity.rs @@ -1734,3 +1734,666 @@ fn lists_of_references_in_other_shapes_match_version_one() { .collect(); columns_match_version_one(&[(PATH, single)], orders); } + +const DEMANDED_CELLS: &str = r#"{ + models: {household: {income: "number", size: "number", assets: "number?", members: "member[]"}, member: {age: "number", earns: "number"}}, + blocks: [ + {expression: "household.need", value: "household.size * 400"}, + {expression: "household.gap", value: "household.need - household.income"}, + {expression: "household.spare", value: "household.income / (household.size - 3)"}, + {expression: "member.share", value: "member.earns * 2"}, + {table: "benefit", inputs: ["household.assets", "household.gap"], outputs: ["household.benefit", "household.tier"], rules: [ + ["> 50000", "", "0", "'ineligible'"], + ["", "<= 0", "0", "'not-needed'"], + ["", "< 200", "200", "'minimum'"], + ["", "", "round(household.gap, 0)", "'top-up'"], + ]}, + {table: "extra", inputs: ["household.gap"], outputs: ["household.extra"], rules: [ + ["> 900", "household.spare"], + ["", "household.gap / 2"], + ]}, + {match: "household.band", arms: [ + ["household.gap > 500", "household.gap * 2"], + ["household.gap > 0", "household.need"], + ["", "0"], + ]}, + {table: "memberBand", inputs: ["member.share", "member.age"], outputs: ["member.band"], rules: [ + ["> 1000", "", "member.share - 1000"], + ["", "< 18", "0"], + ["", "", "member.share"], + ]}, + ], +}"#; + +fn demanded_rows() -> Vec { + (0..80) + .map(|i| { + let members: Vec = (0..i % 3).map(|j| json!({"age": 10 + (i * 7 + j * 11) % 60, "earns": (i * 97 + j * 31) % 900})).collect(); + let mut household = json!({"income": (i * 131) % 2600, "size": 1 + i % 6, "members": members}); + match i % 5 { + 0 => {} + 1 => household["assets"] = Value::Null, + _ => household["assets"] = json!((i * 1777) % 90000), + } + json!({"household": household}) + }) + .collect() +} + +#[test] +fn table_and_match_cells_reading_fields_the_block_already_read_run_typed() { + let policy = r#"{ + models: {household: {income: "number", size: "number", assets: "number?"}}, + blocks: [ + {expression: "household.need", value: "household.size * 400"}, + {expression: "household.gap", value: "household.need - household.income"}, + {table: "benefit", inputs: ["household.assets", "household.gap"], outputs: ["household.benefit", "household.tier"], rules: [ + ["> 50000", "", "0", "'ineligible'"], + ["", "<= 0", "0", "'not-needed'"], + ["", "< 200", "200", "'minimum'"], + ["", "", "round(household.gap, 0)", "'top-up'"], + ]}, + {match: "household.band", arms: [ + ["household.gap > 500", "household.gap * 2"], + ["", "0"], + ]}, + ], + }"#; + let rows: Vec = demanded_rows() + .into_iter() + .enumerate() + .map(|(i, mut row)| { + let household = row["household"].as_object_mut().expect("household"); + household.remove("members"); + household.insert("assets".into(), json!((i * 1777) % 90000)); + row + }) + .collect(); + typed_like_version_one(&[(PATH, policy)], rows); +} + +#[test] +fn cells_reading_already_demanded_and_other_computed_fields_match_version_one() { + let rows = demanded_rows(); + columns_match_version_one(&[(PATH, DEMANDED_CELLS)], rows.clone()); + each_goal( + DEMANDED_CELLS, + &rows, + &[&[], &["household.benefit"], &["household.extra"], &["household.band", "member.band"], &["household.tier"]], + ); + let mut broken = rows; + broken[3]["household"]["income"] = Value::Null; + broken[4]["household"]["size"] = json!(3); + broken[9]["household"]["size"] = json!(3); + broken[7]["household"].as_object_mut().expect("household").remove("size"); + columns_match_version_one(&[(PATH, DEMANDED_CELLS)], broken); +} + +const GATHERED: &str = r#"{ + models: { + account: {structuring: "boolean", volume: "number", corridors: "number?", kind: "string", items: "item[]"}, + item: {price: "number", qty: "number", tag: "string?"}, + }, + blocks: [ + {expression: "account.ratio", value: "account.volume / 100"}, + {table: "alerts", hit: "collect", inputs: ["account.structuring", "account.ratio", "account.corridors"], outputs: ["account.alerts"], rules: [ + ["true", "", "", "'structuring'"], + ["", "> 3", "", "'volume-spike'"], + ["", "", "> 0", "'high-risk-corridor'"], + ]}, + {table: "notes", inputs: ["account.kind", "account.ratio"], outputs: ["account.notes[]", "account.codes[]"], rules: [ + ["'retail'", "", "'retail'", "1"], + ["", "> 5", "account.ratio * 2", ""], + ["'retail', 'sme'", "< 2", "", "account.volume % 7"], + ["", "", "'seen'", "{code: 9}"], + ]}, + {table: "both", inputs: ["account.kind"], outputs: ["account.marks[]", "account.marks[]"], rules: [ + ["'sme'", "'a'", "'b'"], + ["", "", "'c'"], + ]}, + {expression: "account.decision", value: "'structuring' in account.alerts ? 'file' : len(account.alerts) > 0 ? 'look' : 'none'"}, + {expression: "item.total", value: "item.price * item.qty"}, + {table: "flags", inputs: ["item.total", "item.tag"], outputs: ["item.flags[]"], rules: [ + ["> 500", "", "'big'"], + ["", "'gift'", "'gift'"], + ["< 10", "", "'small'"], + ]}, + {expression: "account.flagged", value: "count(account.items, len(#.flags) > 0)"}, + ], +}"#; + +fn gathered_rows() -> Vec { + let kinds = ["retail", "sme", "corp"]; + (0..90) + .map(|i| { + let items: Vec = (0..i % 4) + .map(|j| { + let mut item = json!({"price": (i * 13 + j * 29) % 300, "qty": 1 + (i + j) % 4}); + if (i + j) % 3 == 0 { + item["tag"] = json!((["gift", "plain"])[(i + j) % 2]); + } + item + }) + .collect(); + let mut account = json!({"structuring": i % 7 == 0, "volume": (i * 53) % 900, "kind": kinds[i % 3], "items": items}); + match i % 8 { + 0 => {} + 1 => account["corridors"] = Value::Null, + _ => account["corridors"] = json!(i % 3), + } + json!({"account": account}) + }) + .collect() +} + +#[test] +fn collect_tables_run_typed() { + let policy = r#"{ + models: {account: {structuring: "boolean", volume: "number", corridors: "number"}}, + blocks: [ + {expression: "account.ratio", value: "account.volume / 100"}, + {table: "alerts", hit: "collect", inputs: ["account.structuring", "account.ratio", "account.corridors"], outputs: ["account.alerts"], rules: [ + ["true", "", "", "'structuring'"], + ["", "> 3", "", "'volume-spike'"], + ["", "", "> 0", "'high-risk-corridor'"], + ["false", "> 8", "", "account.ratio"], + ]}, + {expression: "account.decision", value: "'structuring' in account.alerts ? 'file' : len(account.alerts) > 0 ? 'look' : 'none'"}, + ], + }"#; + let rows: Vec = (0..90) + .map(|i| json!({"account": {"structuring": i % 7 == 0, "volume": (i * 53) % 900, "corridors": i % 3}})) + .collect(); + typed_like_version_one(&[(PATH, policy)], rows); +} + +#[test] +fn collect_tables_with_several_outputs_members_and_failures_match_version_one() { + let rows = gathered_rows(); + columns_match_version_one(&[(PATH, GATHERED)], rows.clone()); + each_goal( + GATHERED, + &rows, + &[&[], &["account.alerts"], &["account.decision"], &["account.flagged"], &["account.notes", "account.marks"]], + ); + let mut broken = rows; + broken[2]["account"]["volume"] = Value::Null; + broken[5]["account"]["kind"] = json!(4); + broken[9]["account"]["items"][0]["price"] = json!("x"); + broken[11]["account"].as_object_mut().expect("account").remove("structuring"); + broken[13]["account"]["corridors"] = json!("many"); + columns_match_version_one(&[(PATH, GATHERED)], broken); +} + +#[test] +fn collect_cells_that_fail_only_on_unmatched_rules_match_version_one() { + let policy = r#"{ + models: {order: {qty: "number", price: "number", code: "string?"}}, + blocks: [ + {table: "notes", hit: "collect", inputs: ["order.qty"], outputs: ["order.notes"], rules: [ + ["> 0", "order.price / order.qty"], + ["0", "'empty'"], + ["< 0", "len(order.code)"], + ["", "order.qty"], + ]}, + ], + }"#; + let rows: Vec = (0..64) + .map(|i| { + let mut order = json!({"qty": (i % 5) as i64 - 2, "price": 10 * i}); + if i % 3 == 0 { + order["code"] = json!("abc"); + } + json!({"order": order}) + }) + .collect(); + columns_match_version_one(&[(PATH, policy)], rows); +} + +const SPARSE_FIELDS: &str = r#"{ + models: { + employer: {bonus: "number?", region: "string?", audited: "boolean?", employees: "employee[]"}, + employee: {salary: "number", smoker: "boolean?", grade: "string?", extra: "number?"}, + }, + blocks: [ + {expression: "employee.rate", value: "(employee.smoker ?? false) ? 1.5 : 1"}, + {expression: "employee.label", value: "(employee.grade ?? 'none') + '-' + string(employee.salary)"}, + {expression: "employee.pay", value: "employee.salary * employee.rate + (employee.extra ?? 0)"}, + {expression: "employer.total", value: "sum(map(employer.employees, #.pay)) + (employer.bonus ?? 0)"}, + {expression: "employer.where", value: "employer.region == null ? 'unknown' : employer.region"}, + {expression: "employer.checked", value: "employer.audited == true"}, + ], +}"#; + +fn optional_rows() -> Vec { + (0..120) + .map(|i| { + let employees: Vec = (0..i % 4) + .map(|j| { + let mut e = json!({"salary": 1000 + (i * 17 + j * 5) % 300}); + match (i + j) % 4 { + 0 => {} + 1 => e["smoker"] = Value::Null, + 2 => e["smoker"] = json!(true), + _ => e["smoker"] = json!(false), + } + match (i + 2 * j) % 3 { + 0 => {} + 1 => e["grade"] = Value::Null, + _ => e["grade"] = json!((["a", "b"])[j % 2]), + } + match (i + j) % 5 { + 0 => e["extra"] = Value::Null, + 1 | 2 => e["extra"] = json!((i * j) % 9), + _ => {} + } + e + }) + .collect(); + let mut employer = json!({"employees": employees}); + match i % 3 { + 0 => {} + 1 => { + employer["bonus"] = Value::Null; + employer["region"] = Value::Null; + employer["audited"] = Value::Null; + } + _ => { + employer["bonus"] = json!(i % 11); + employer["region"] = json!((["north", "south"])[i % 2]); + employer["audited"] = json!(i % 2 == 0); + } + } + json!({"employer": employer}) + }) + .collect() +} + +#[test] +fn optional_fields_given_as_null_or_left_out_run_typed() { + typed_like_version_one(&[(PATH, SPARSE_FIELDS)], optional_rows()); +} + +#[test] +fn optional_fields_given_as_null_left_out_or_wrongly_typed_match_version_one() { + let mut rows = optional_rows(); + rows[5]["employer"]["employees"][0]["smoker"] = json!("yes"); + rows[6]["employer"]["bonus"] = json!("big"); + rows[9]["employer"]["employees"][0]["extra"] = json!(true); + columns_match_version_one(&[(PATH, SPARSE_FIELDS)], rows.clone()); + each_goal(SPARSE_FIELDS, &rows, &[&[], &["employee.rate"], &["employer.where"], &["employer.total"]]); +} + +const TRANSITIVE_CELLS: &str = r#"{ + models: { + invoice: {amount: "number", paid: "number", vip: "boolean", lines: "line[]"}, + line: {qty: "number", price: "number"}, + }, + blocks: [ + {expression: "invoice.outstanding", value: "invoice.amount - invoice.paid"}, + {expression: "invoice.overdue", value: "invoice.outstanding > 100"}, + {match: "invoice.stage", arms: [ + ["invoice.outstanding <= 0", "'paid'"], + ["invoice.overdue and invoice.vip", "'soft'"], + ["invoice.overdue", "'hard'"], + ["", "'open'"], + ]}, + {table: "fees", inputs: ["invoice.stage"], outputs: ["invoice.fee"], rules: [ + ["'hard'", "round(invoice.outstanding * 0.1, 2)"], + ["'soft'", "invoice.outstanding / (invoice.paid - 50)"], + ["", "0"], + ]}, + {assertion: "invoice.ok", conditions: ["invoice.fee < 1000", "invoice.outstanding < 5000"]}, + {match: "invoice.payment", arms: [ + ["invoice.ok", "invoice.fee + invoice.outstanding"], + ["", "0"], + ]}, + {expression: "line.total", value: "line.qty * line.price"}, + {expression: "line.big", value: "line.total > 50"}, + {match: "line.charge", arms: [ + ["line.big", "line.total * 0.9"], + ["", "line.total"], + ]}, + ], +}"#; + +fn transitive_rows() -> Vec { + (0..96) + .map(|i| { + let lines: Vec = (0..i % 3).map(|j| json!({"qty": 1 + (i + j) % 4, "price": (i * 7 + j * 13) % 40})).collect(); + json!({"invoice": {"amount": (i * 97) % 3000, "paid": (i * 31) % 700, "vip": i % 5 == 0, "lines": lines}}) + }) + .collect() +} + +#[test] +fn cells_reading_fields_demanded_through_other_blocks_run_typed() { + let rows: Vec = transitive_rows() + .into_iter() + .enumerate() + .map(|(i, mut row)| { + row["invoice"]["paid"] = json!(100 + (i * 31) % 600); + row + }) + .collect(); + typed_like_version_one(&[(PATH, TRANSITIVE_CELLS)], rows); +} + +#[test] +fn cells_reading_fields_demanded_through_other_blocks_match_version_one() { + let rows = transitive_rows(); + columns_match_version_one(&[(PATH, TRANSITIVE_CELLS)], rows.clone()); + each_goal( + TRANSITIVE_CELLS, + &rows, + &[&[], &["invoice.fee"], &["invoice.payment"], &["line.charge"], &["invoice.stage", "invoice.ok"]], + ); +} + +const MIXED_GATHER: &str = r#"{ + models: {customer: {age: "number", pep: "boolean", docs: "boolean", country: "string", score: "number?", accounts: "account[]"}, account: {balance: "number", kind: "string"}}, + blocks: [ + {match: "customer.risk", arms: [["customer.pep", "'high'"], ["customer.country in ['NO', 'SE']", "'low'"], ["", "'medium'"]]}, + {table: "outcome", inputs: ["customer.docs", "customer.risk"], outputs: ["customer.outcome", "customer.reasons[]", "customer.level"], rules: [ + ["false", "", "'reject'", "'identity'", ""], + ["", "'high'", "'refer'", "'pep'", "3"], + ["", "'medium'", "", "'review'", "customer.age / 10"], + ["", "", "'accept'", "", "1"], + ]}, + {table: "points", inputs: ["customer.score"], outputs: ["customer.points[]", "customer.first"], rules: [ + ["> 700", "customer.score - 700", "'top'"], + ["> 500", "10", ""], + ["", "0", "customer.score * 2"], + ]}, + {table: "accountFlags", inputs: ["account.balance", "account.kind"], outputs: ["account.flags[]", "account.tier"], rules: [ + ["< 0", "", "'overdrawn'", "'watch'"], + ["", "'savings'", "'saver'", ""], + ["> 10000", "", "'large'", "'gold'"], + ]}, + {expression: "customer.summary", value: "customer.outcome + ':' + string(len(customer.reasons))"}, + {expression: "account.label", value: "string(account.tier ?? 0) + '/' + string(account.balance)"}, + {expression: "customer.levelText", value: "string(customer.level ?? 0)"}, + ], +}"#; + +fn mixed_rows() -> Vec { + (0..90) + .map(|i| { + let accounts: Vec = (0..i % 3) + .map(|j| json!({"balance": (i as i64 * 977 + j as i64 * 131) % 20000 - 3000, "kind": (["savings", "current"])[(i + j) % 2]})) + .collect(); + let mut customer = json!({"age": 18 + i % 60, "pep": i % 9 == 0, "docs": i % 11 != 0, "country": (["NO", "DE", "SE", "FR"])[i % 4], "accounts": accounts}); + if i % 6 != 0 { + customer["score"] = json!(300 + (i * 37) % 600); + } + json!({"customer": customer}) + }) + .collect() +} + +#[test] +fn collect_tables_with_first_hit_outputs_match_version_one() { + let rows = mixed_rows(); + columns_match_version_one(&[(PATH, MIXED_GATHER)], rows.clone()); + each_goal( + MIXED_GATHER, + &rows, + &[&[], &["customer.outcome"], &["customer.level", "account.tier"], &["customer.summary"], &["customer.first"], &["account.label", "customer.levelText"]], + ); +} + +#[test] +fn collect_tables_with_first_hit_outputs_run_typed() { + let policy = r#"{ + models: {customer: {pep: "boolean", docs: "boolean", country: "string"}}, + blocks: [ + {match: "customer.risk", arms: [["customer.pep", "'high'"], ["customer.country in ['NO', 'SE']", "'low'"], ["", "'medium'"]]}, + {table: "outcome", inputs: ["customer.docs", "customer.risk"], outputs: ["customer.outcome", "customer.reasons[]"], rules: [ + ["false", "", "'reject'", "'identity'"], + ["", "'high'", "'refer'", "'pep'"], + ["", "", "'accept'", ""], + ]}, + {expression: "customer.summary", value: "customer.outcome + ':' + string(len(customer.reasons))"}, + ], + }"#; + let rows: Vec = (0..90) + .map(|i| json!({"customer": {"pep": i % 9 == 0, "docs": i % 11 != 0, "country": (["NO", "DE", "SE", "FR"])[i % 4]}})) + .collect(); + typed_like_version_one(&[(PATH, policy)], rows); +} + +const POWERS: &str = r#"{ + models: {loan: {amount: "number", rate: "number", years: "number", step: "number?"}}, + blocks: [ + {expression: "loan.factor", value: "(1 + loan.rate / 1200) ^ (-loan.years * 12)"}, + {expression: "loan.payment", value: "round(loan.amount * (loan.rate / 1200) / (1 - loan.factor), 2)"}, + {expression: "loan.grown", value: "loan.amount * 1.01 ^ loan.years"}, + {expression: "loan.stepped", value: "2 ^ (loan.step ?? 3)"}, + ], +}"#; + +#[test] +fn powers_with_computed_exponents_run_typed() { + let rows: Vec = (0..80) + .map(|i| json!({"loan": {"amount": 10000 + 997 * i, "rate": 1 + (i % 9), "years": 5 + (i % 26), "step": i % 7}})) + .collect(); + typed_like_version_one(&[(PATH, POWERS)], rows); +} + +#[test] +fn powers_with_fractional_missing_or_huge_exponents_match_version_one() { + let rows: Vec = (0..80) + .map(|i| { + let mut loan = json!({"amount": 10000 + 997 * i, "rate": 1 + (i % 9), "years": 5 + (i % 26)}); + match i % 6 { + 0 => {} + 1 => loan["step"] = Value::Null, + 2 => loan["step"] = json!(0.5), + 3 => loan["step"] = json!(-2), + 4 => loan["step"] = json!(400), + _ => loan["step"] = json!(2.25), + } + if i % 13 == 0 { + loan["years"] = json!(2.5); + } + json!({"loan": loan}) + }) + .collect(); + columns_match_version_one(&[(PATH, POWERS)], rows); +} + +const VALIDATED: &str = r#"{ + models: {trip: {kind: "string(leisure|business)", tags: "string[]", scores: "number[]", flags: "boolean[]", travellers: "traveller[]"}, traveller: {seat: "string(aisle|window)", meals: "string[]"}}, + blocks: [ + {expression: "trip.label", value: "trip.kind + ':' + string(len(trip.tags)) + ':' + string(sum(trip.scores))"}, + {expression: "traveller.picky", value: "len(traveller.meals) > 1 or traveller.seat == 'window'"}, + {expression: "trip.picky", value: "count(trip.travellers, #.picky)"}, + ], +}"#; + +#[test] +fn enum_and_primitive_array_inputs_validate_like_version_one() { + let mut rows: Vec = (0..80) + .map(|i| { + let travellers: Vec = (0..i % 3) + .map(|j| json!({"seat": (["aisle", "window"])[(i + j) % 2], "meals": (0..(i + j) % 3).map(|k| format!("m{k}")).collect::>()})) + .collect(); + json!({"trip": {"kind": (["leisure", "business"])[i % 2], "tags": (0..i % 4).map(|k| format!("t{k}")).collect::>(), "scores": (0..i % 3).map(|k| k * 2).collect::>(), "flags": [i % 2 == 0], "travellers": travellers}}) + }) + .collect(); + rows[3]["trip"]["kind"] = json!("Leisure"); + rows[5]["trip"]["kind"] = json!(""); + rows[7]["trip"]["tags"] = json!(["a", 1]); + rows[9]["trip"]["tags"] = json!(["a", null, "b"]); + rows[11]["trip"]["scores"] = json!([1, "2"]); + rows[13]["trip"]["flags"] = json!([true, null, 0]); + rows[15]["trip"]["scores"] = json!([null]); + rows[17]["trip"]["travellers"] = json!([{"seat": "middle", "meals": []}]); + rows[19]["trip"]["travellers"] = json!([{"seat": "aisle", "meals": ["x", false]}]); + rows[21]["trip"]["tags"] = json!("not a list"); + columns_match_version_one(&[(PATH, VALIDATED)], rows); +} + +const NESTED_VALIDATED: &str = r#"{ + dictionaries: {plan: [["B", "Basic"], ["P", "Plus"]]}, + models: { + employer: {employees: "employee[]"}, + employee: {salary: "number", dependents: "dependent[]"}, + dependent: {relation: "string(spouse|child)", dob: "date", plan: "plan?", notes: "string[]", pets: "pet[]"}, + pet: {kind: "string", age: "number?"}, + }, + blocks: [ + {expression: "employee.deps", value: "count(employee.dependents, #.relation == 'child' and d().diff(#.dob, 'year') < 26)"}, + {expression: "employer.total", value: "sum(map(employer.employees, #.salary + #.deps * 10))"}, + ], +}"#; + +#[test] +fn nested_member_objects_validate_like_version_one() { + let mut rows: Vec = (0..60) + .map(|i| { + let employees: Vec = (0..1 + i % 3) + .map(|j| { + let dependents: Vec = (0..(i + j) % 3) + .map(|k| json!({"relation": (["spouse", "child"])[(i + k) % 2], "dob": format!("20{:02}-0{}-1{}", (i + k) % 25, 1 + k % 9, k % 9), "notes": ["a"], "pets": [{"kind": "cat"}]})) + .collect(); + json!({"salary": 1000 + i * 10 + j, "dependents": dependents}) + }) + .collect(); + json!({"employer": {"employees": employees}}) + }) + .collect(); + let deps = |rows: &mut Vec, at: usize| -> Value { + rows[at]["employer"]["employees"][0]["dependents"] = json!([{"relation": "child", "dob": "2010-01-01"}]); + rows[at]["employer"]["employees"][0]["dependents"][0].clone() + }; + for (at, field, value) in [ + (2, "relation", json!("cousin")), + (4, "dob", json!("2010-02-30")), + (6, "dob", json!(12)), + (8, "plan", json!("X")), + (10, "plan", json!("P")), + (12, "notes", json!(["x", 3])), + (14, "notes", json!("x")), + (16, "pets", json!([{"kind": 5}])), + (18, "pets", json!([{"kind": "dog", "age": "old"}])), + (20, "pets", json!([null, {"kind": "dog", "extra": [1, 2]}])), + (22, "dob", json!("")), + (24, "relation", Value::Null), + ] { + let mut dependent = deps(&mut rows, at); + dependent[field] = value; + rows[at]["employer"]["employees"][0]["dependents"][0] = dependent; + } + rows[26]["employer"]["employees"][0]["dependents"] = json!([5]); + rows[28]["employer"]["employees"][0]["dependents"] = json!([null]); + columns_match_version_one(&[(PATH, NESTED_VALIDATED)], rows); +} + +const OTHER_LISTS: &str = r#"{ + globals: {rules: {hazardous: "string[]"}}, + models: { + claim: {kind: "string", received: "string[]", travellers: "traveller[]"}, + traveller: {activities: "string[]", age: "number"}, + }, + blocks: [ + {expression: "claim.required", value: "claim.kind == 'theft' ? ['police', 'invoice'] : claim.kind == 'water' ? ['photos'] : []"}, + {expression: "claim.missing", value: "filter(claim.required, not (# in claim.received))"}, + {expression: "claim.count", value: "len(claim.missing)"}, + {expression: "traveller.hazard", value: "some(traveller.activities, # in hazardous)"}, + {expression: "claim.hazards", value: "count(claim.travellers, #.hazard)"}, + ], +}"#; + +fn other_list_rows() -> Vec { + let kinds = ["theft", "water", "fire"]; + let docs = ["police", "invoice", "photos", "estimate"]; + let acts = ["ski", "dive", "walk", "read"]; + (0..90) + .map(|i| { + let received: Vec<&str> = (0..i % 4).map(|k| docs[(i + k) % 4]).collect(); + let travellers: Vec = (0..i % 3) + .map(|j| json!({"age": 20 + j, "activities": (0..(i + j) % 3).map(|k| acts[(i + j + k) % 4]).collect::>()})) + .collect(); + json!({"hazardous": ["ski", "dive"], "claim": {"kind": kinds[i % 3], "received": received, "travellers": travellers}}) + }) + .collect() +} + +#[test] +fn membership_in_another_list_runs_typed() { + let policy = r#"{ + models: {claim: {required: "string[]", received: "string[]"}}, + blocks: [ + {expression: "claim.missing", value: "filter(claim.required, not (# in claim.received))"}, + {expression: "claim.count", value: "count(claim.required, # in claim.received)"}, + ], + }"#; + let docs = ["police", "invoice", "photos", "estimate"]; + let rows: Vec = (0..80) + .map(|i| json!({"claim": {"required": (0..i % 3).map(|k| docs[(i + k) % 4]).collect::>(), "received": (0..i % 4).map(|k| docs[(i * 3 + k) % 4]).collect::>()}})) + .collect(); + typed_like_version_one(&[(PATH, policy)], rows); +} + +#[test] +fn membership_in_another_list_or_a_global_list_matches_version_one() { + let mut rows = other_list_rows(); + columns_match_version_one(&[(PATH, OTHER_LISTS)], rows.clone()); + each_goal(OTHER_LISTS, &rows, &[&[], &["claim.missing"], &["traveller.hazard"], &["claim.count", "claim.hazards"]]); + rows[3]["claim"]["received"] = Value::Null; + rows[5]["hazardous"] = Value::Null; + rows[7]["claim"]["received"] = json!(["police", null]); + rows[9]["claim"]["received"] = json!([1, "police"]); + columns_match_version_one(&[(PATH, OTHER_LISTS)], rows); +} + +const LIFTED_DATES: &str = r#"{ + models: { + trip: {start: "date", end: "date?", travellers: "traveller[]"}, + traveller: {dob: "date", since: "date?"}, + }, + blocks: [ + {expression: "traveller.age", value: "trip.start.diff(traveller.dob, 'year')"}, + {expression: "traveller.member", value: "traveller.since == null ? 0 : trip.start.diff(traveller.since, 'day')"}, + {expression: "traveller.late", value: "trip.end != null and traveller.dob < trip.end"}, + {expression: "trip.oldest", value: "max(map(trip.travellers, #.age))"}, + ], +}"#; + +#[test] +fn member_blocks_reading_root_dates_run_typed() { + let rows: Vec = (0..80) + .map(|i| { + let travellers: Vec = (0..1 + i % 3) + .map(|j| json!({"dob": format!("19{:02}-0{}-1{}", 50 + (i + j) % 49, 1 + j % 9, i % 9), "since": format!("2020-0{}-01", 1 + (i + j) % 9)})) + .collect(); + json!({"trip": {"start": format!("2025-0{}-1{}", 1 + i % 9, i % 10), "end": format!("2025-1{}-01", i % 3), "travellers": travellers}}) + }) + .collect(); + typed_like_version_one(&[(PATH, LIFTED_DATES)], rows); +} + +#[test] +fn member_blocks_reading_root_dates_in_any_form_match_version_one() { + let starts = ["2025-03-20", "2025-03-20T23:30:00-05:00", "2024-02-29T12:00:00Z", "2025-01-01 10:00", "2025-13-01", ""]; + let rows: Vec = (0..72) + .map(|i| { + let travellers: Vec = (0..i % 3) + .map(|j| { + let mut t = json!({"dob": (["1990-05-05", "2000-02-29T08:00:00+05:30", "1985-12-31"])[(i + j) % 3]}); + if (i + j) % 4 == 0 { + t["since"] = Value::Null; + } + t + }) + .collect(); + let mut trip = json!({"start": starts[i % starts.len()], "travellers": travellers}); + if i % 5 != 0 { + trip["end"] = json!(starts[(i + 2) % starts.len()]); + } + json!({"trip": trip}) + }) + .collect(); + columns_match_version_one(&[(PATH, LIFTED_DATES)], rows); +} diff --git a/core/engine/tests/typed_parity.rs b/core/engine/tests/typed_parity.rs index 2cfb1fff..ebd274e8 100644 --- a/core/engine/tests/typed_parity.rs +++ b/core/engine/tests/typed_parity.rs @@ -2242,3 +2242,31 @@ fn membership_in_the_list_being_iterated_runs_typed() { ]; columns_match_version_one(expression("filter(nums, # * 2 in nums)"), mixed); } + +#[test] +fn membership_in_another_list_of_the_row_matches_version_one() { + let rows = vec![ + json!({"a": ["x", "y", "z"], "b": ["y"], "n": [1, 2, 3], "m": [2, 5]}), + json!({"a": ["x"], "b": [], "n": [], "m": [1]}), + json!({"a": [], "b": ["x"], "n": [4], "m": []}), + json!({"a": ["q", null], "b": ["q", null], "n": [1, null], "m": [null]}), + json!({"a": ["p"], "b": null, "n": [7], "m": null}), + json!({"a": null, "b": ["p"], "n": null, "m": [7]}), + json!({"a": ["r", "s"], "b": ["s", "r"], "n": [8, 9], "m": [9, 8, 7]}), + ]; + for source in [ + "filter(a, not (# in b))", + "filter(a, # in b)", + "some(a, # in b)", + "count(n, # in m)", + "map(filter(n, # in m), # * 2)", + "all(a, # not in b)", + ] { + columns_match_version_one(expression(source), rows.clone()); + } + let clean: Vec = rows.iter().filter(|row| !row.to_string().contains("null")).cloned().collect(); + let paths = columns_match_version_one(expression("filter(a, not (# in b))"), clean.clone()); + assert!(paths.typed > 0 && paths.laned == 0, "{paths:?}"); + let paths = columns_match_version_one(expression("count(n, # in m)"), clean); + assert!(paths.typed > 0 && paths.laned == 0, "{paths:?}"); +} diff --git a/core/expression/src/typed/build.rs b/core/expression/src/typed/build.rs index 2093ebed..27914075 100644 --- a/core/expression/src/typed/build.rs +++ b/core/expression/src/typed/build.rs @@ -1402,7 +1402,7 @@ impl<'h> Build<'h> { }); d } - Op::InRow(a, list, field) => { + Op::InRow(a, list, field, of) => { let ra = rof(self, a); let va = self.val(*a)?; let d = self.fresh()?; @@ -1412,6 +1412,7 @@ impl<'h> Build<'h> { ra, list: *list, field: *field, + of: *of, }); d } diff --git a/core/expression/src/typed/date.rs b/core/expression/src/typed/date.rs index fbfbec90..aaaedb83 100644 --- a/core/expression/src/typed/date.rs +++ b/core/expression/src/typed/date.rs @@ -389,8 +389,23 @@ impl<'e, 'x> Exec<'e, 'x> { match rep { Rep::Date => { let shift = Dates::shift(&kind, &consts)?; + let mut last: Option<(Date, Date)> = None; self.each(act, &skip, |i| match this.given(start, i) { - Some(Given::Date(x)) => d.dates[i] = shift.apply(&x), + Some(Given::Date(x)) => { + d.dates[i] = match last { + Some((seen, shifted)) + if seen == x + && seen.0.map(|at| at.timezone()) == x.0.map(|at| at.timezone()) => + { + shifted + } + _ => { + let shifted = shift.apply(&x); + last = Some((x, shifted)); + shifted + } + } + } _ => broken.push(i), }); } diff --git a/core/expression/src/typed/exec.rs b/core/expression/src/typed/exec.rs index 912b7dfc..957eb993 100644 --- a/core/expression/src/typed/exec.rs +++ b/core/expression/src/typed/exec.rs @@ -1191,8 +1191,10 @@ impl<'e, 'x> Exec<'e, 'x> { ra, list, field, + of, } => Self::def(regs, *dst, |d, regs| { let lists = self.feeds.lists.get(*list as usize); + let from = of.and_then(|of| self.feeds.lists.get(of as usize)); let feed = self .feeds .fields @@ -1241,7 +1243,24 @@ impl<'e, 'x> Exec<'e, 'x> { if Bits::get(&d.fault, i) { continue; } - let row = lists.parent[start + i] as usize; + let row = match (of, from) { + (None, _) => lists.parent[start + i] as usize, + (Some(_), Some(from)) => { + let row = from.root[start + i] as usize; + let gone = |bits: &Option>| { + bits.as_ref().is_some_and(|bits| Bits::get(bits, row)) + }; + if gone(&lists.null) || gone(&lists.faulted) { + Bits::set(&mut d.fault, i, true); + continue; + } + row + } + (Some(_), None) => { + Bits::set(&mut d.fault, i, true); + continue; + } + }; let (lo, hi) = (lists.offsets[row] as usize, lists.offsets[row + 1] as usize); let mut hit = false; let mut bad = false; diff --git a/core/expression/src/typed/hir.rs b/core/expression/src/typed/hir.rs index 6ee4a146..efa1b992 100644 --- a/core/expression/src/typed/hir.rs +++ b/core/expression/src/typed/hir.rs @@ -144,7 +144,7 @@ pub enum Op { If(NodeId, NodeId, NodeId), Coalesce(NodeId, NodeId), InSet(NodeId, Vec), - InRow(NodeId, ListId, u16), + InRow(NodeId, ListId, u16, Option), InRange(NodeId, Range), Fold { fold: Fold, @@ -393,7 +393,7 @@ impl Hir { | Op::InRange(..) | Op::Clock(Clock::Matches, _) | Op::Host(Host::Method(_), _) => false, - Op::Checked(_) | Op::Clock(Clock::Strict, _) => true, + Op::Checked(_) | Op::Parent(_) | Op::Clock(Clock::Strict, _) => true, Op::Coalesce(..) | Op::Pick(..) => true, Op::If(c, ..) if !from(c) => true, _ => return true, @@ -456,7 +456,7 @@ impl Op { Op::If(c, t, e) => Op::If(f(*c), f(*t), f(*e)), Op::Coalesce(a, b) => Op::Coalesce(f(*a), f(*b)), Op::InSet(a, set) => Op::InSet(f(*a), set.clone()), - Op::InRow(a, list, field) => Op::InRow(f(*a), *list, *field), + Op::InRow(a, list, field, of) => Op::InRow(f(*a), *list, *field, *of), Op::InRange(a, r) => Op::InRange(f(*a), *r), Op::Fold { fold, @@ -745,7 +745,7 @@ impl Hir { Op::Or(a, b) => format!("or %{a}, %{b}"), Op::If(c, t, e) => format!("if %{c} then %{t} else %{e}"), Op::Coalesce(a, b) => format!("coalesce %{a}, %{b}"), - Op::InRow(a, list, field) => format!("inrow %{a} list {list} field {field}"), + Op::InRow(a, list, field, of) => format!("inrow %{a} list {list} field {field} of {of:?}"), Op::InSet(a, set) => format!( "inset %{a} [{}]", set.iter() diff --git a/core/expression/src/typed/ins.rs b/core/expression/src/typed/ins.rs index 0a8a61bf..b7d42d27 100644 --- a/core/expression/src/typed/ins.rs +++ b/core/expression/src/typed/ins.rs @@ -185,6 +185,7 @@ pub(crate) enum Ins { ra: Rep, list: u16, field: u16, + of: Option, }, InRangeFix { dst: R, diff --git a/core/expression/src/typed/lower.rs b/core/expression/src/typed/lower.rs index 47bf5291..df2a2553 100644 --- a/core/expression/src/typed/lower.rs +++ b/core/expression/src/typed/lower.rs @@ -604,10 +604,7 @@ impl Lowering { self.output("", *cond, ctx.scope, true)?; } for (rule, cond) in spec.rules.iter().zip(&conds) { - for value in &rule.values { - let source = value - .as_deref() - .ok_or_else(|| Unsupported::new("empty collect output cell"))?; + for source in rule.values.iter().flatten() { let id = self.parse(source, false, ctx, r)?; let null = self.konst(Lit::Null); let (arms, ty) = self.unify(vec![id, null])?; @@ -1611,8 +1608,10 @@ impl Lowering { divisor.is_none_or(|d| d.is_zero() || Self::fractional(d)), ), Arith::Rem => Ty::new(Kind::Num(None), divisor.is_none_or(|d| d.is_zero())), - Arith::Pow if divisor.is_some_and(|d| d.scale == 0) => Ty::num(None), - Arith::Pow => return Err(Unsupported::new("exponent must be an integer literal")), + Arith::Pow if divisor.is_some_and(|d| !d.decimal().fract().is_zero()) => { + return Err(Unsupported::new("exponent must be an integer")) + } + Arith::Pow => Ty::num(None), }; let (scope, ids) = self.scoped(&[a, b])?; Ok(self.add(Op::Arith(op, ids[0], ids[1]), ty, scope)) @@ -2803,6 +2802,9 @@ impl Lowering { { return self.in_row(x, seq); } + if let Some(found) = self.in_root(x, seq) { + return found; + } let item = self.item(seq)?; let test = self.belongs(x, item)?; let test = self.lifted(test, seq.list)?; @@ -2810,6 +2812,31 @@ impl Lowering { self.checked(x, found) } + fn in_root(&mut self, x: NodeId, seq: Seq) -> Option { + let Scope::Elem(of) = self.nodes[x as usize].scope else { + return None; + }; + if of == seq.list + || seq.keep.is_some() + || seq.value.is_some() + || self.schema.lists[seq.list as usize].parent.is_some() + { + return None; + } + let field = self.schema.field(seq.list, "")?; + let ty = self.schema.lists[seq.list as usize].fields[field as usize].ty; + match (self.kind(x), ty.kind) { + (Kind::Num(_), Kind::Num(_)) | (Kind::Bool, Kind::Bool) | (Kind::Text, Kind::Text) => {} + _ => return None, + } + let found = self.add( + Op::InRow(x, seq.list, field, Some(of)), + Ty::boolean(), + Scope::Elem(of), + ); + Some(self.checked(x, found)) + } + fn in_row(&mut self, x: NodeId, seq: Seq) -> Lowered { let refused = || Unsupported::new("membership in the enclosing list"); if seq.keep.is_some() @@ -2825,7 +2852,7 @@ impl Lowering { _ => return Err(refused()), } let found = self.add( - Op::InRow(x, seq.list, field), + Op::InRow(x, seq.list, field, None), Ty::boolean(), Scope::Elem(seq.list), ); diff --git a/core/expression/src/typed/num.rs b/core/expression/src/typed/num.rs index 3e609e89..ee661c82 100644 --- a/core/expression/src/typed/num.rs +++ b/core/expression/src/typed/num.rs @@ -180,6 +180,7 @@ impl Exact { Arith::Mul => x.checked_mul(y).map(Some).ok_or(Fault), Arith::Div => Ok(x.checked_div(y)), Arith::Rem => Ok(x.checked_rem(y)), + Arith::Pow if !y.fract().is_zero() => Err(Fault), Arith::Pow => x .checked_powd(y) .or_else(|| Decimal::from_f64(x.to_f64()?.powf(y.to_f64()?))) diff --git a/core/expression/src/typed/tests/interp.rs b/core/expression/src/typed/tests/interp.rs index 21eb6903..5a076f32 100644 --- a/core/expression/src/typed/tests/interp.rs +++ b/core/expression/src/typed/tests/interp.rs @@ -323,11 +323,21 @@ impl<'a, 'x> Interp<'a, 'x> { set.iter().any(|lit| Self::equal(&x, &Self::lit(lit))), )) } - Op::InRow(a, list, field) => { + Op::InRow(a, list, field, of) => { let x = self.eval(*a)?; let feeds = self.feeds; let l = &feeds.lists[*list as usize]; - let row = l.parent[self.elem[*list as usize]] as usize; + let row = match of { + None => l.parent[self.elem[*list as usize]] as usize, + Some(of) => feeds.lists[*of as usize].root[self.elem[*of as usize]] as usize, + }; + if of.is_some() + && [&l.null, &l.faulted] + .iter() + .any(|bits| bits.as_ref().is_some_and(|bits| Bits::get(bits, row))) + { + return Err(Fault); + } let (lo, hi) = (l.offsets[row] as usize, l.offsets[row + 1] as usize); let feed = &feeds.fields[*list as usize][*field as usize]; let mut hit = false; diff --git a/core/expression/src/typed/tests/lower.rs b/core/expression/src/typed/tests/lower.rs index 6cbd0a8c..047f71b2 100644 --- a/core/expression/src/typed/tests/lower.rs +++ b/core/expression/src/typed/tests/lower.rs @@ -388,7 +388,6 @@ fn unsupported_shapes() { ("empty template", "``"), ("unsupported path", "c.weird + 1"), ("null arithmetic", "c.absent + 1"), - ("variable exponent", "c.n ^ c.n"), ("fractional exponent", "c.n ^ 0.5"), ("round to variable places", "round(c.n, c.n)"), ("bool of a number", "bool(c.n)"),