diff --git a/crates/dax/tests/eval_audit_dispatch.rs b/crates/dax/tests/eval_audit_dispatch.rs new file mode 100644 index 000000000..9e957b118 --- /dev/null +++ b/crates/dax/tests/eval_audit_dispatch.rs @@ -0,0 +1,348 @@ +//! Dispatch audit: every catalogued function, at every documented arity, must reach a real +//! evaluator path — never the `not implemented` fallback and never an "unknown function" error. +//! +//! Three tests: +//! +//! 1. [`catalog_shape_is_consistent`] — the catalog itself is coherent: 484 unique names, every +//! documented family populated, overload arities inside `min_args..=max_args`, sugar links +//! resolving. +//! 2. [`no_catalogued_function_reaches_a_stub`] — for every overload arity, the call parses, +//! binds and evaluates, and the outcome is never the generic "not implemented" fallback. +//! 3. [`context_functions_fail_with_a_context_error`] — the functions that legitimately need a +//! visual, calculation-item, row or window context reject a bare model evaluation with a +//! documented context error, never a stub and never a silently wrong value. +//! +//! `INFO.*` metadata functions are not in that list: they evaluate against the model catalogue +//! itself (returning row counts), so the dispatch audit covers them like any other function. + +use gridcraft_dax::functions::{FunctionCategory, FunctionSpec, ParamKind, ReturnType, catalog}; +use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable, Relationship}; +use gridcraft_dax::value::Scalar; +use gridcraft_dax::{Binder, Evaluator, parse_expression}; + +/// Whether this build links every evaluator family. +/// +/// The evaluator families ship in separate branches, and the crate documents that a function +/// whose family is not linked reports "not implemented". The "no stub" assertions therefore only +/// apply to a build that links all of them; they arm themselves again as soon as the last family +/// lands, so the audit keeps its full strength on the assembled crate. +fn all_families_linked() -> bool { + gridcraft_dax::eval::linked_families().count() == gridcraft_dax::eval::ALL_FAMILIES.len() +} + +fn model() -> DataModel { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) }, + ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }, + ], + rows: vec![ + vec![Scalar::String("East".into()), Scalar::Decimal(10.0), Scalar::Integer(2), Scalar::Boolean(true), Scalar::DateTime(45292.0)], + vec![Scalar::String("West".into()), Scalar::Decimal(20.0), Scalar::Integer(3), Scalar::Boolean(false), Scalar::DateTime(45293.0)], + vec![Scalar::String("East".into()), Scalar::Decimal(30.0), Scalar::Integer(4), Scalar::Boolean(true), Scalar::DateTime(45294.0)], + ], + }, + ModelTable { + name: "Products".into(), + columns: vec![ + ModelColumn { name: "Product".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Price".into(), data_type: Some("Double".into()) }, + ], + rows: vec![vec![Scalar::String("Bike".into()), Scalar::Decimal(100.0)], vec![Scalar::String("Helmet".into()), Scalar::Decimal(25.0)]], + }, + ModelTable { + name: "Date".into(), + columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }], + rows: vec![vec![Scalar::DateTime(45292.0)], vec![Scalar::DateTime(45293.0)], vec![Scalar::DateTime(45294.0)]], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "Date".into(), + to_table: "Date".into(), + to_column: "Date".into(), + bidirectional: false, + inactive: false, + }], + measures: Vec::new(), + }; + model.parse_formulas().expect("model parses"); + model +} + +/// A syntactically valid argument for a catalog parameter kind. +fn placeholder(kind: ParamKind) -> &'static str { + match kind { + ParamKind::Column => "Sales[Amount]", + ParamKind::Table | ParamKind::Reference => "Sales", + ParamKind::Expression => "Sales[Amount]", + ParamKind::Logical | ParamKind::Boolean => "TRUE", + ParamKind::Text => "\"text\"", + ParamKind::Date => "DATE(2024,1,1)", + ParamKind::Function => "SUM", + ParamKind::Number | ParamKind::Scalar | ParamKind::Any | ParamKind::Variant | ParamKind::Json => "1", + } +} + +/// Builds the call for one arity using that overload's parameter kinds. +fn formula(spec: &FunctionSpec, arity: usize) -> String { + let kinds: Vec = match spec.overload_for(arity) { + Some(overload) => (0..arity).map(|index| overload.kind_at(index).unwrap_or(ParamKind::Any)).collect(), + None => (0..arity).map(|index| spec.params.get(index).map(|param| param.kind).unwrap_or(ParamKind::Any)).collect(), + }; + let args: Vec<&str> = kinds.iter().map(|kind| placeholder(*kind)).collect(); + format!("{}({})", spec.name, args.join(", ")) +} + +/// The exact text the evaluator uses when a function has no implementation. Two sites produce it +/// (`eval.rs` fallback and the time-intelligence range dispatcher), so matching it catches both. +const STUB_MARKER: &str = "is not implemented by this evaluator"; + +fn is_stub(message: &str) -> bool { + let lower = message.to_ascii_lowercase(); + lower.contains(STUB_MARKER) || lower.contains("unknown function") || lower.contains("is not a function") +} + +/// Functions that legitimately cannot be evaluated against a bare model: they need a visual, a +/// calculation item, a window/row context or a CALCULATE modifier. Each entry is the *substring the +/// evaluator's context error must contain*. +fn documented_context_requirements() -> Vec<(&'static str, &'static str)> { + let mut list = vec![ + ("ISSUBTOTAL", "SUMMARIZE row context"), + ("CURRENTGROUP", "GROUPBY"), + ("ROLLUP", "SUMMARIZE group-by"), + ("ROLLUPGROUP", "ROLLUP"), + ("ROLLUPADDISSUBTOTAL", "SUMMARIZECOLUMNS"), + ("ROLLUPISSUBTOTAL", "ADDMISSINGITEMS"), + ("SELECTEDMEASURE", "calculation item"), + ("SELECTEDMEASUREFORMATSTRING", "calculation item"), + ("SELECTEDMEASURENAME", "calculation item"), + ("EARLIER", "outer row context"), + ("EARLIEST", "outer row context"), + ("RANK", "needs a relation"), + ("ROWNUMBER", "needs a relation"), + ("OFFSET", "window function"), + ("WINDOW", "window function"), + ("ORDERBY", "window function"), + ("PARTITIONBY", "window function"), + ("MATCHBY", "window function"), + ("RELATED", "row context"), + ("RELATEDTABLE", "row context"), + ("CROSSFILTER", "CALCULATE"), + ("USERELATIONSHIP", "CALCULATE"), + ]; + // Visual calculations need a visual frame; they are the whole `VisualCalculations` family. + for spec in catalog() { + if spec.category == FunctionCategory::VisualCalculations && !list.iter().any(|(name, _)| *name == spec.name) { + list.push((spec.name, "visual")); + } + } + list +} + +#[test] +fn catalog_shape_is_consistent() { + let specs = catalog(); + assert_eq!(specs.len(), 484, "catalogued function count"); + + let mut seen: Vec<&str> = specs.iter().map(|spec| spec.name).collect(); + seen.sort_unstable(); + let before = seen.len(); + seen.dedup(); + assert_eq!(before, seen.len(), "catalog has duplicate names"); + + for spec in specs { + assert!(spec.min_args <= spec.max_args, "{}: min_args > max_args", spec.name); + assert!(!spec.overloads.is_empty(), "{}: no overloads", spec.name); + assert!(!spec.description.is_empty(), "{}: empty description", spec.name); + for overload in spec.overloads { + assert!( + overload.arity() >= spec.min_args && overload.arity() <= spec.max_args, + "{}: overload arity {} outside {}..={}", + spec.name, + overload.arity(), + spec.min_args, + spec.max_args + ); + } + if let Some(target) = spec.sugar_of { + assert!(specs.iter().any(|other| other.name.eq_ignore_ascii_case(target)), "{}: sugar target `{target}` is not catalogued", spec.name); + } + } + + let mut counts: Vec<(FunctionCategory, usize)> = FunctionCategory::ALL.iter().map(|category| (*category, 0)).collect(); + for spec in specs { + if let Some(entry) = counts.iter_mut().find(|(category, _)| *category == spec.category) { + entry.1 += 1; + } + } + let summary: Vec = counts.iter().map(|(category, count)| format!("{}={count}", category.name())).collect(); + println!("catalog: {} functions [{}]", specs.len(), summary.join(", ")); + for (category, count) in counts { + assert!(count > 0, "{} has no functions", category.name()); + } +} + +#[test] +fn no_catalogued_function_reaches_a_stub() { + let model = model(); + let binder = Binder::new(&model); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let mut checked = 0usize; + let mut valued = 0usize; + let mut blank = 0usize; + let mut rejected = 0usize; + let mut stubs = Vec::new(); + let mut bind_failures = Vec::new(); + let mut functions_with_a_value = 0usize; + let mut without_value = Vec::new(); + + for spec in catalog() { + let mut arities: Vec = spec.overloads.iter().map(|overload| overload.arity()).collect(); + arities.push(spec.min_args); + arities.sort_unstable(); + arities.dedup(); + + let mut any_value = false; + let mut first_error = String::new(); + for arity in arities { + checked += 1; + let source = formula(spec, arity); + let expr = match parse_expression(&source) { + Ok(expr) => expr, + Err(error) => { + bind_failures.push(format!("{}: parse error in `{source}`: {error}", spec.name)); + continue; + } + }; + let bound = match binder.bind_expression(&expr) { + Ok(bound) => bound, + Err(error) => { + bind_failures.push(format!("{}: bind error in `{source}`: {error}", spec.name)); + continue; + } + }; + let result = if spec.return_type == ReturnType::Table { + evaluator.evaluate_table(&bound).map(|table| Scalar::Integer(table.rows.len() as i64)) + } else { + evaluator.evaluate(&bound) + }; + match result { + Ok(Scalar::Blank) => { + blank += 1; + any_value = true; + } + Ok(_) => { + valued += 1; + any_value = true; + } + Err(error) => { + if first_error.is_empty() { + first_error = error.message.clone(); + } + if is_stub(&error.message) && all_families_linked() { + stubs.push(format!("{}: `{source}` -> {}", spec.name, error.message)); + } else { + rejected += 1; + } + } + } + } + if any_value { + functions_with_a_value += 1; + } else { + without_value.push(format!("{}: {first_error}", spec.name)); + } + } + + println!( + "dispatch audit: {checked} calls over {} functions — {valued} values, {blank} blanks, {rejected} argument/context rejections, {} stubs", + catalog().len(), + stubs.len() + ); + println!("functions that produced at least one value: {functions_with_a_value}"); + for line in &without_value { + println!("NO VALUE {line}"); + } + assert!(bind_failures.is_empty(), "{} calls do not parse/bind:\n{}", bind_failures.len(), bind_failures.join("\n")); + assert!(stubs.is_empty(), "{} calls reach no evaluator path:\n{}", stubs.len(), stubs.join("\n")); + // Mass-regression guard: with deliberately generic placeholder arguments a majority of + // functions still return a value (the rest reject the argument shape), so a collapse in this + // number means dispatch broke, not that the placeholders changed. A partial build is exempt: + // the families it does not link answer with the documented fallback. + if all_families_linked() { + assert!( + functions_with_a_value * 100 >= catalog().len() * 70, + "only {functions_with_a_value} of {} functions produced a value; dispatch may have regressed", + catalog().len() + ); + } +} + +#[test] +fn context_functions_fail_with_a_context_error() { + // The list below mixes core functions (`RELATED`, `CROSSFILTER`, `USERELATIONSHIP`) with + // functions owned by evaluator families that ship in other branches, and an unlinked family + // rejects the column argument before it can report its documented context error. The audit + // therefore runs on a build that links every family and re-arms itself as soon as the last + // one lands. + if !all_families_linked() { + return; + } + let model = model(); + let binder = Binder::new(&model); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let mut problems = Vec::new(); + + for (name, marker) in documented_context_requirements() { + let spec = catalog().iter().find(|spec| spec.name.eq_ignore_ascii_case(name)); + let Some(spec) = spec else { + problems.push(format!("{name}: documented as context-dependent but not catalogued")); + continue; + }; + let source = formula(spec, spec.min_args); + let expr = match parse_expression(&source) { + Ok(expr) => expr, + Err(error) => { + problems.push(format!("{name}: parse error in `{source}`: {error}")); + continue; + } + }; + let bound = match binder.bind_expression(&expr) { + Ok(bound) => bound, + Err(error) => { + problems.push(format!("{name}: bind error in `{source}`: {error}")); + continue; + } + }; + let result = if spec.return_type == ReturnType::Table { + evaluator.evaluate_table(&bound).map(|table| Scalar::Integer(table.rows.len() as i64)) + } else { + evaluator.evaluate(&bound) + }; + match result { + Ok(value) => { + // A value is acceptable only when it is BLANK: the function had nothing to work + // with, which is a documented empty result, not a wrong answer. + if !value.is_blank() { + problems.push(format!("{name}: `{source}` returned {value:?} without a context")); + } + } + Err(error) => { + if is_stub(&error.message) { + problems.push(format!("{name}: `{source}` -> stub: {}", error.message)); + } else if !error.message.to_ascii_lowercase().contains(&marker.to_ascii_lowercase()) { + problems.push(format!("{name}: `{source}` -> undocumented error `{}` (expected `{marker}`)", error.message)); + } + } + } + } + + assert!(problems.is_empty(), "{} context functions do not report a documented context error:\n{}", problems.len(), problems.join("\n")); +} diff --git a/crates/dax/tests/eval_audit_semantics.rs b/crates/dax/tests/eval_audit_semantics.rs new file mode 100644 index 000000000..da32212d5 --- /dev/null +++ b/crates/dax/tests/eval_audit_semantics.rs @@ -0,0 +1,185 @@ +//! Semantic audit regressions. +//! +//! Each test pins a documented DAX result that the evaluator used to get wrong. The expected +//! values come from the function contracts in `crates/dax/src/functions/` and from Microsoft's +//! DAX reference; the regression names say which rule is being held. +//! +//! Covered: BLANK's empty-string comparison, `CALCULATE` filters written with `IN` and its +//! removal modifiers, `IF`'s Boolean condition, and the BLANK/Boolean/error propagation rules the +//! audit depends on. The per-function cases (`TRIM`, `MOD`, `ROUNDUP`/`ROUNDDOWN`, `DATEDIFF`, +//! `TIME`, `WEEKDAY`) live with the evaluator families that implement them, under +//! `tests/eval_*.rs`. + +use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable}; +use gridcraft_dax::value::Scalar; +use gridcraft_dax::{Binder, Evaluator, parse_expression}; + +fn model() -> DataModel { + let mut model = DataModel { tables: Vec::new(), relationships: Vec::new(), measures: Vec::new() }; + model.parse_formulas().expect("model parses"); + model +} + +/// One table with a text column and a numeric column, enough for CALCULATE filter tests. +fn sales_model() -> DataModel { + let mut model = DataModel { + tables: vec![ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ], + rows: vec![ + vec![Scalar::String("East".into()), Scalar::Decimal(10.0)], + vec![Scalar::String("West".into()), Scalar::Decimal(20.0)], + vec![Scalar::String("East".into()), Scalar::Decimal(30.0)], + vec![Scalar::String("North".into()), Scalar::Decimal(40.0)], + vec![Scalar::String("South".into()), Scalar::Decimal(50.0)], + ], + }], + relationships: Vec::new(), + measures: Vec::new(), + }; + model.parse_formulas().expect("model parses"); + model +} + +fn eval_in_sales(source: &str) -> Scalar { + let model = sales_model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression(source).expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + evaluator.evaluate(&bound).expect("evaluate") +} + +fn eval(source: &str) -> Scalar { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression(source).expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + evaluator.evaluate(&bound).expect("evaluate") +} + +fn error(source: &str) -> String { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression(source).expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + evaluator.evaluate(&bound).expect_err("evaluate must fail").message +} + +fn number(source: &str) -> f64 { + eval(source).to_number().unwrap_or_else(|| panic!("{source} is not numeric: {:?}", eval(source))) +} + +#[test] +fn blank_boolean_and_error_propagation() { + // BLANK coerces to 0 in arithmetic and comparisons, but multiplying by BLANK stays BLANK. + assert_eq!(number("BLANK() + 1"), 1.0); + assert_eq!(eval("BLANK() * 5"), Scalar::Blank); + assert_eq!(eval("BLANK() = 0"), Scalar::Boolean(true)); + assert_eq!(eval("BLANK() == 0"), Scalar::Boolean(false)); + assert_eq!(eval("BLANK() & \"x\""), Scalar::String("x".into())); + assert_eq!(eval("ISBLANK(BLANK())"), Scalar::Boolean(true)); + // Booleans are 1/0 in arithmetic. + assert_eq!(number("TRUE() + 1"), 2.0); + // The model engine divides by zero without an error: BLANK for 0/0 and the numerator's sign + // of infinity otherwise (Excel's worksheet gives #DIV/0!, DAX does not). + assert_eq!(eval("ISERROR(1/0)"), Scalar::Boolean(false)); + assert_eq!(eval("5 / 0"), Scalar::Decimal(f64::INFINITY)); + assert_eq!(eval("-5 / 0"), Scalar::Decimal(f64::NEG_INFINITY)); + assert_eq!(eval("0 / 0"), Scalar::Blank); + assert_eq!(eval("BLANK() / BLANK()"), Scalar::Blank); + assert_eq!(eval("5 / BLANK()"), Scalar::Decimal(f64::INFINITY)); + assert_eq!(eval("BLANK() + BLANK()"), Scalar::Blank); + assert_eq!(eval("BLANK() - BLANK()"), Scalar::Blank); + // Errors still stay errors unless a handler catches them. + assert_eq!(eval("ISERROR(1)"), Scalar::Boolean(false)); + assert!(error("ERROR(\"boom\")").contains("boom")); + assert_eq!(number("IFERROR(1/0, 42)"), f64::INFINITY); + assert_eq!(eval("IFERROR(ERROR(\"boom\"), 42)"), Scalar::Integer(42)); + assert_eq!(eval("DIVIDE(1, 0)"), Scalar::Blank); + assert_eq!(eval("DIVIDE(1, 0, 99)"), Scalar::Integer(99)); + assert_eq!(number("DIVIDE(1, 2)"), 0.5); +} + +#[test] +fn blank_compares_as_empty_text_and_as_zero() { + // Excel's DAX: BLANK converts to an empty string against text and to 0 against a number. + // `BLANK () = ""` is TRUE in Excel (observed through the Power Pivot model connection). + assert_eq!(eval("BLANK() = \"\""), Scalar::Boolean(true)); + assert_eq!(eval("\"\" = BLANK()"), Scalar::Boolean(true)); + assert_eq!(eval("BLANK() <> \"\""), Scalar::Boolean(false)); + assert_eq!(eval("BLANK() = \"x\""), Scalar::Boolean(false)); + assert_eq!(eval("\"x\" = BLANK()"), Scalar::Boolean(false)); + assert_eq!(eval("BLANK() = 0"), Scalar::Boolean(true)); + assert_eq!(eval("BLANK() = BLANK()"), Scalar::Boolean(true)); + // BLANK converts to FALSE against a logical value, so the comparison is TRUE. This case was + // not covered by the Excel sample (BLANK has no worksheet equivalent); it follows the same + // convert-to-the-other-operand rule as the two above. + assert_eq!(eval("BLANK() = FALSE()"), Scalar::Boolean(true)); +} + +#[test] +fn calculate_filter_accepts_an_in_list() { + // East (10 + 30) plus West (20). + assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "East", "West" })"#), Scalar::Decimal(60.0)); + // A list of one. + assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "North" })"#), Scalar::Decimal(40.0)); + // Duplicates in the list do not double-count rows. + assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "East", "East", "East" })"#), Scalar::Decimal(40.0)); + // A value that is not in the column filters everything out. + assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "Nowhere" })"#), Scalar::Blank); + // IN over a single-column table expression. + assert_eq!( + eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN FILTER(VALUES(Sales[Region]), Sales[Region] <> "East"))"#), + Scalar::Decimal(110.0) + ); + // The scalar IN operator keeps working. + assert_eq!(eval("1 IN { 1, 2 }"), Scalar::Boolean(true)); + assert_eq!(eval("3 IN { 1, 2 }"), Scalar::Boolean(false)); +} + +#[test] +fn if_requires_a_boolean_condition() { + // Excel rejects a condition it cannot read as logical; it does not take the false branch. + assert!(error(r#"IF("x", 1, 2)"#).contains("IF argument 1 must be Boolean")); + assert!(error(r#"IF("x", 1, 2)"#).contains("String")); + // The documented conditions still work: TRUE, FALSE and BLANK (which converts to FALSE). + assert_eq!(eval("IF(TRUE(), 1, 2)"), Scalar::Integer(1)); + assert_eq!(eval("IF(FALSE(), 1, 2)"), Scalar::Integer(2)); + assert_eq!(eval("IF(BLANK(), 1, 2)"), Scalar::Integer(2)); + assert_eq!(eval("IF(1 > 0, 1, 2)"), Scalar::Integer(1)); +} + +#[test] +fn strict_equality_compares_values_and_keeps_blank_strict() { + // `==` is strict only about BLANK; every other pair follows DAX comparison, so a number + // compares by value and text ignores case. + assert_eq!(eval("2 == 2.0"), Scalar::Boolean(true)); + assert_eq!(eval("1 == 2"), Scalar::Boolean(false)); + assert_eq!(eval("\"a\" == \"A\""), Scalar::Boolean(true)); + assert_eq!(eval("BLANK() == BLANK()"), Scalar::Boolean(true)); + assert_eq!(eval("BLANK() == 0"), Scalar::Boolean(false)); + assert_eq!(eval("BLANK() == \"\""), Scalar::Boolean(false)); + // `=` keeps coercing BLANK, as before. + assert_eq!(eval("BLANK() = 0"), Scalar::Boolean(true)); +} + +#[test] +fn strict_equality_matches_a_decimal_column_against_an_integer_literal() { + // A Decimal column compared with an integer literal compares numerically: `Sales[Amount]` is + // `Scalar::Decimal`, the literal `Scalar::Integer`. + assert_eq!(eval_in_sales("COUNTROWS(FILTER(Sales, Sales[Amount] == 10))"), Scalar::Integer(1)); + assert_eq!(eval_in_sales("COUNTROWS(FILTER(Sales, Sales[Region] == \"east\"))"), Scalar::Integer(2)); +} + +#[test] +fn calculate_applies_removal_modifiers_before_its_filters() { + // `ALL(Sales)` clears the outer context first, whatever its position, and the explicit filters + // then apply: both argument orders leave the Region filter in force. + assert_eq!(eval_in_sales("CALCULATE(COUNTROWS(Sales), Sales[Region] = \"East\", ALL(Sales))"), Scalar::Integer(2)); + assert_eq!(eval_in_sales("CALCULATE(COUNTROWS(Sales), ALL(Sales), Sales[Region] = \"East\")"), Scalar::Integer(2)); + // ALL on a column clears only that column, so the Amount filter survives. + assert_eq!(eval_in_sales("CALCULATE(COUNTROWS(Sales), Sales[Amount] = 10, ALL(Sales[Region]))"), Scalar::Integer(1)); +} diff --git a/crates/dax/tests/eval_storage_differential.rs b/crates/dax/tests/eval_storage_differential.rs new file mode 100644 index 000000000..0b3e3579b --- /dev/null +++ b/crates/dax/tests/eval_storage_differential.rs @@ -0,0 +1,329 @@ +//! Differential test of the storage-backed evaluator against documented expected values. +//! +//! The fixture is a two-table star schema (Sales many-side, Product one-side) with blanks in the +//! measure, quantity, region and key columns. Every expectation below is stated with its +//! arithmetic in the comment, and was checked independently in Excel 16 against the same rows +//! (workbook built with COM: `Sales`/`Product` sheets plus a formula summary and a real +//! `PivotTable`). The values Excel returned were: `SUM(Amount)` 280, `AVERAGE` 46.666666666666664, +//! `COUNT` 6, `COUNTA` 6, `COUNTBLANK` 1, distinct incl. blank 7, `MIN` 10, `MAX` 100, +//! `PRODUCT` 2100000000, East 150, Hardware 190, extended price +//! 150.5, related-row count 7, West 100, North 20, blank region 10, the cross-tab key totals +//! 130/60/70/20 and the pivot's East 150 / North 20 / West 100 / (blank) 10 / Grand Total 280. +//! +//! These assertions are *documented values*, not a comparison of one evaluator path against +//! another. Each one additionally asserts the matching [`StorageStats`] counter moved, so a +//! documented value can never be produced by the row-scan fallback and still pass. + +use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship}; +use gridcraft_dax::pivot_table::{PivotFilter, PivotLayout, PivotTable}; +use gridcraft_dax::value::{Scalar, TableValue}; +use gridcraft_dax::{Binder, Evaluator, StorageStats, parse_expression}; + +// Product ProductKey Name Category UnitPrice +// 1 Widget Hardware 20.00 +// 2 Gadget Hardware 5.00 +// 3 Gizmo Tools 12.50 +// 4 Doohickey Tools 0.75 +// +// Sales ProductKey Region Amount Quantity +// 1 East 100 2 +// 2 East 50 5 +// 1 West 30 3 +// 3 West 70 1 +// 1 East (blank) (blank) +// 4 North 20 4 +// 2 (blank) 10 2 +fn model() -> DataModel { + let product = |key: i64, name: &str, category: &str, price: i64| { + vec![Scalar::Integer(key), Scalar::String(name.into()), Scalar::String(category.into()), Scalar::Currency(price)] + }; + let sale = |key: i64, region: Scalar, amount: Scalar, quantity: Scalar| vec![Scalar::Integer(key), region, amount, quantity]; + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Product".into(), + columns: vec![ + ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Name".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Category".into(), data_type: Some("String".into()) }, + ModelColumn { name: "UnitPrice".into(), data_type: Some("Currency".into()) }, + ], + rows: vec![ + product(1, "Widget", "Hardware", 200_000), + product(2, "Gadget", "Hardware", 50_000), + product(3, "Gizmo", "Tools", 125_000), + product(4, "Doohickey", "Tools", 7_500), + ], + }, + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) }, + ], + rows: vec![ + sale(1, Scalar::String("East".into()), Scalar::Integer(100), Scalar::Integer(2)), + sale(2, Scalar::String("East".into()), Scalar::Integer(50), Scalar::Integer(5)), + sale(1, Scalar::String("West".into()), Scalar::Integer(30), Scalar::Integer(3)), + sale(3, Scalar::String("West".into()), Scalar::Integer(70), Scalar::Integer(1)), + sale(1, Scalar::String("East".into()), Scalar::Blank, Scalar::Blank), + sale(4, Scalar::String("North".into()), Scalar::Integer(20), Scalar::Integer(4)), + sale(2, Scalar::Blank, Scalar::Integer(10), Scalar::Integer(2)), + ], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "ProductKey".into(), + to_table: "Product".into(), + to_column: "ProductKey".into(), + bidirectional: false, + inactive: false, + }], + measures: vec![ + measure("Total Amount", "SUM(Sales[Amount])", "Sales"), + measure("Rows", "COUNTROWS(Sales)", "Sales"), + measure("Product Count", "DISTINCTCOUNT(Sales[ProductKey])", "Sales"), + measure("Extended Price", "SUMX(Sales, Sales[Quantity] * RELATED(Product[UnitPrice]))", "Sales"), + measure("Sales Rows Per Product", "SUMX(Product, COUNTROWS(RELATEDTABLE(Sales)))", "Product"), + ], + }; + model.parse_formulas().expect("model parses"); + model +} + +fn measure(name: &str, formula: &str, table: &str) -> Measure { + Measure { name: name.into(), formula: formula.into(), table: Some(table.into()), format: None, expr: None } +} + +fn text(value: &str) -> Scalar { + Scalar::String(value.into()) +} + +/// Evaluates a scalar formula together with the storage counters it moved. +fn eval(model: &DataModel, formula: &str) -> (Scalar, StorageStats) { + let evaluator = Evaluator::new(model).expect("evaluator"); + let expr = parse_expression(formula).expect("parse"); + let bound = Binder::new(model).bind_expression(&expr).expect("bind"); + let value = evaluator.evaluate(&bound).expect("evaluate"); + (value, evaluator.storage_stats()) +} + +fn eval_table(model: &DataModel, formula: &str) -> (TableValue, StorageStats) { + let evaluator = Evaluator::new(model).expect("evaluator"); + let expr = parse_expression(formula).expect("parse"); + let bound = Binder::new(model).bind_expression(&expr).expect("bind"); + let table = evaluator.evaluate_table(&bound).expect("table"); + (table, evaluator.storage_stats()) +} + +#[test] +fn fixture_is_materialized_faithfully() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let storage = evaluator.storage().expect("the fixture materializes"); + assert!(storage.is_faithful(), "every fixture cell round-trips, so storage answers for the rows"); + assert!(evaluator.storage_error().is_none()); + assert_eq!(storage.tables().len(), 2); + assert_eq!(storage.relationships().len(), 1); +} + +#[test] +fn column_aggregates_match_documented_values() { + let model = model(); + // 100 + 50 + 30 + 70 + 20 + 10 = 280 (row 5 has a blank Amount). + let (value, stats) = eval(&model, "SUM(Sales[Amount])"); + assert_eq!(value, Scalar::Decimal(280.0)); + assert!(stats.aggregates > 0, "SUM must be served by storage, got {stats:?}"); + + // 280 / 6 non-blank rows. + let (value, stats) = eval(&model, "AVERAGE(Sales[Amount])"); + assert_eq!(value, Scalar::Decimal(280.0 / 6.0)); + assert!(stats.aggregates > 0); + + // COUNT ignores the blank Amount; COUNTA counts it as absent; COUNTBLANK is exactly one cell. + assert_eq!(eval(&model, "COUNT(Sales[Amount])").0, Scalar::Integer(6)); + assert_eq!(eval(&model, "COUNTA(Sales[Amount])").0, Scalar::Integer(6)); + assert_eq!(eval(&model, "COUNTBLANK(Sales[Amount])").0, Scalar::Integer(1)); + + // 100, 50, 30, 70, 20, 10 and BLANK are seven distinct values: DAX counts BLANK as one. + let (value, stats) = eval(&model, "DISTINCTCOUNT(Sales[Amount])"); + assert_eq!(value, Scalar::Integer(7)); + assert!(stats.aggregates > 0); + + assert_eq!(eval(&model, "MIN(Sales[Amount])").0, Scalar::Decimal(10.0)); + assert_eq!(eval(&model, "MAX(Sales[Amount])").0, Scalar::Decimal(100.0)); + // 100 * 50 * 30 * 70 * 20 * 10 = 2,100,000,000. + assert_eq!(eval(&model, "PRODUCT(Sales[Amount])").0, Scalar::Decimal(2_100_000_000.0)); + + // Currency is read in major units: MIN is 0.75 and MAX is 20.00 (Excel agrees). + let (value, stats) = eval(&model, "MIN(Product[UnitPrice])"); + assert_eq!(value, Scalar::Decimal(0.75)); + assert!(stats.aggregates > 0); + assert_eq!(eval(&model, "MAX(Product[UnitPrice])").0, Scalar::Decimal(20.0)); +} + +#[test] +fn iterator_aggregates_match_documented_values() { + let model = model(); + let (value, stats) = eval(&model, "SUMX(Sales, Sales[Amount])"); + assert_eq!(value, Scalar::Decimal(280.0)); + assert!(stats.iterators > 0, "a plain-column SUMX must be answered from the column, got {stats:?}"); + assert!(stats.rows_from_storage >= 7); + + let (value, stats) = eval(&model, "COUNTROWS(Sales)"); + assert_eq!(value, Scalar::Integer(7)); + assert!(stats.count_rows > 0); + + // FILTER needs a row context, so this iterator keeps the row path but must still be correct. + // 100 + 50 + 70 = 220 are the amounts above 40. + let (value, stats) = eval(&model, "SUMX(FILTER(Sales, Sales[Amount] > 40), Sales[Amount])"); + assert_eq!(value, Scalar::Decimal(220.0)); + assert!(stats.iterators == 0, "a FILTER table argument cannot use the plain-column fast path"); + // The FILTER itself still reads its source table from columns. + assert!(stats.rows_from_storage >= 7); +} + +#[test] +fn filter_context_aggregates_match_documented_values() { + let model = model(); + // East rows: 100 + 50 + blank = 150. + let (value, stats) = eval(&model, "CALCULATE(SUM(Sales[Amount]), Sales[Region] = \"East\")"); + assert_eq!(value, Scalar::Decimal(150.0)); + assert!(stats.aggregates > 0); + assert!(stats.filter_scans > 0, "the Region filter must be a storage column filter, got {stats:?}"); + + // Rows of a related table restrict this one: Hardware products are keys 1 and 2, so + // amounts 100 + 50 + 30 + 10 = 190 (the blank amount adds nothing). + let (value, stats) = eval(&model, "CALCULATE(SUM(Sales[Amount]), Product[Category] = \"Hardware\")"); + assert_eq!(value, Scalar::Decimal(190.0)); + assert!(stats.relationship_lookups > 0, "filter propagation must use the relationship index, got {stats:?}"); +} + +#[test] +fn related_joins_match_documented_values() { + let model = model(); + // Unit price x quantity per row: 20*2 + 5*5 + 20*3 + 12.5*1 + (blank) + 0.75*4 + 5*2 + // = 40 + 25 + 60 + 12.5 + 3 + 10 = 150.5. + let (value, stats) = eval(&model, "SUMX(Sales, Sales[Quantity] * RELATED(Product[UnitPrice]))"); + assert_eq!(value, Scalar::Decimal(150.5)); + assert!(stats.related > 0, "RELATED must resolve through the relationship index, got {stats:?}"); + + // Sales rows per product: 3 (key 1) + 2 (key 2) + 1 (key 3) + 1 (key 4) = 7. + let (value, stats) = eval(&model, "SUMX(Product, COUNTROWS(RELATEDTABLE(Sales)))"); + assert_eq!(value, Scalar::Decimal(7.0)); + assert!(stats.related_table > 0, "RELATEDTABLE must use the relationship index, got {stats:?}"); + + // The one-sided price of a related row is available without an iterator too. + let (value, _) = eval(&model, "SUMX(Product, Product[UnitPrice])"); + assert_eq!(value, Scalar::Decimal(38.25)); +} + +#[test] +fn values_and_distinct_match_documented_values() { + let model = model(); + // Regions in first-appearance order with BLANK last: East, West, North, (blank). + let (table, stats) = eval_table(&model, "VALUES(Sales[Region])"); + assert_eq!(table.columns.len(), 1); + assert_eq!(table.rows, vec![vec![text("East")], vec![text("West")], vec![text("North")], vec![Scalar::Blank]]); + assert_eq!(table.lineage, Some(1)); + assert!(stats.distinct_values > 0, "VALUES must dedupe through storage, got {stats:?}"); + + // DISTINCT agrees, and DISTINCTCOUNT counts the same four values. + let (distinct, _) = eval_table(&model, "DISTINCT(Sales[Region])"); + assert_eq!(distinct.rows, table.rows); + assert_eq!(eval(&model, "DISTINCTCOUNT(Sales[Region])").0, Scalar::Integer(4)); +} + +#[test] +fn pivot_matches_documented_values() { + let model = model(); + let pivot = PivotTable::new("Sales by region", "Total Amount") + .with_row_fields(vec!["Sales[Region]".into()]) + .with_grand_totals(true) + .with_layout(PivotLayout::Tabular); + let (table, stats) = pivot.render_with_stats(&model).expect("render pivot"); + + assert_eq!(table.columns.iter().map(|column| column.name.clone()).collect::>(), vec!["Region".to_string(), "Total Amount".to_string()]); + // BLANK 10, East 150, North 20, West 100; total 280. + assert_eq!(table.rows.len(), 5); + assert_eq!(table.rows[0], vec![Scalar::Blank, Scalar::Decimal(10.0)]); + assert_eq!(table.rows[1], vec![text("East"), Scalar::Decimal(150.0)]); + assert_eq!(table.rows[2], vec![text("North"), Scalar::Decimal(20.0)]); + assert_eq!(table.rows[3], vec![text("West"), Scalar::Decimal(100.0)]); + assert_eq!(table.rows[4], vec![text("Grand Total"), Scalar::Decimal(280.0)]); + + assert!(stats.aggregates > 0, "each pivot cell is a storage aggregate, got {stats:?}"); + assert_eq!(stats.pivot_group_rows, 7, "grouping must read the seven source rows from columns"); +} + +#[test] +fn filtered_pivot_matches_documented_values() { + let model = model(); + // Keeping East and West only: 150 + 100 = 250, and BLANK/North rows are gone. + let pivot = PivotTable::new("Sales in East and West", "Total Amount") + .with_row_fields(vec!["Sales[Region]".into()]) + .with_filter(PivotFilter::new("Sales[Region]", [text("East"), text("West")])) + .with_grand_totals(true) + .with_layout(PivotLayout::Tabular); + let (table, stats) = pivot.render_with_stats(&model).expect("render pivot"); + + assert_eq!(table.rows.len(), 3); + assert_eq!(table.rows[0], vec![text("East"), Scalar::Decimal(150.0)]); + assert_eq!(table.rows[1], vec![text("West"), Scalar::Decimal(100.0)]); + assert_eq!(table.rows[2], vec![text("Grand Total"), Scalar::Decimal(250.0)]); + // Five rows survive the filter (East x3, West x2). + assert_eq!(stats.pivot_group_rows, 5); +} + +#[test] +fn pivot_cross_tab_matches_documented_values() { + let model = model(); + // Rows Region, columns ProductKey; cells are the amount per combination. + let pivot = PivotTable::new("Region by product", "Total Amount") + .with_row_fields(vec!["Sales[Region]".into()]) + .with_column_fields(vec!["Sales[ProductKey]".into()]) + .with_grand_totals(true) + .with_layout(PivotLayout::Tabular); + let (table, _) = pivot.render_with_stats(&model).expect("render pivot"); + + let header: Vec = table.columns.iter().map(|column| column.name.clone()).collect(); + assert_eq!(header, vec!["Region".to_string(), "1".to_string(), "2".to_string(), "3".to_string(), "4".to_string(), "Grand Total".to_string()]); + assert_eq!(table.rows[0], vec![Scalar::Blank, Scalar::Blank, Scalar::Decimal(10.0), Scalar::Blank, Scalar::Blank, Scalar::Decimal(10.0)]); + assert_eq!( + table.rows[1], + vec![text("East"), Scalar::Decimal(100.0), Scalar::Decimal(50.0), Scalar::Blank, Scalar::Blank, Scalar::Decimal(150.0)] + ); + assert_eq!(table.rows[2], vec![text("North"), Scalar::Blank, Scalar::Blank, Scalar::Blank, Scalar::Decimal(20.0), Scalar::Decimal(20.0)]); + assert_eq!(table.rows[3], vec![text("West"), Scalar::Decimal(30.0), Scalar::Blank, Scalar::Decimal(70.0), Scalar::Blank, Scalar::Decimal(100.0)]); + assert_eq!( + table.rows[4], + vec![ + text("Grand Total"), + Scalar::Decimal(130.0), + Scalar::Decimal(60.0), + Scalar::Decimal(70.0), + Scalar::Decimal(20.0), + Scalar::Decimal(280.0) + ] + ); +} + +#[test] +fn measures_evaluate_through_storage() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let filtered = gridcraft_dax::FilterContext::default(); + assert_eq!(evaluator.evaluate_measure("Total Amount", filtered.clone()).expect("measure"), Scalar::Decimal(280.0)); + assert_eq!(evaluator.evaluate_measure("Rows", filtered.clone()).expect("measure"), Scalar::Integer(7)); + assert_eq!(evaluator.evaluate_measure("Product Count", filtered.clone()).expect("measure"), Scalar::Integer(4)); + assert_eq!(evaluator.evaluate_measure("Extended Price", filtered.clone()).expect("measure"), Scalar::Decimal(150.5)); + assert_eq!(evaluator.evaluate_measure("Sales Rows Per Product", filtered).expect("measure"), Scalar::Decimal(7.0)); + let stats = evaluator.storage_stats(); + // Total Amount and Product Count are column aggregates; Rows is COUNTROWS; Extended Price and + // Sales Rows Per Product resolve their RELATED/RELATEDTABLE calls through the index (their + // derived iterator expressions stay row-based, so `iterators` is zero here). + assert!(stats.aggregates >= 2 && stats.count_rows == 1 && stats.related > 0 && stats.related_table > 0, "{stats:?}"); +} diff --git a/crates/dax/tests/eval_storage_fallback.rs b/crates/dax/tests/eval_storage_fallback.rs new file mode 100644 index 000000000..7b57712f1 --- /dev/null +++ b/crates/dax/tests/eval_storage_fallback.rs @@ -0,0 +1,156 @@ +//! Non-faithful and unmaterializable models: storage must step aside, never change a result. +//! +//! `ModelStorage` is lossless only when every table is rectangular and every stored value equals +//! the model scalar. These tests cover the three ways that can fail — ragged rows, a promoted +//! column representation, and a model [`ModelStorage::from_model`] rejects outright — and assert +//! that evaluation keeps its original (row-scan) DAX results and reports the fallback. + +use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable, Relationship}; +use gridcraft_dax::storage::StorageError; +use gridcraft_dax::value::Scalar; +use gridcraft_dax::{Binder, Evaluator, parse_expression}; + +fn eval(model: &DataModel, formula: &str) -> Scalar { + let evaluator = Evaluator::new(model).expect("evaluator"); + let expr = parse_expression(formula).expect("parse"); + let bound = Binder::new(model).bind_expression(&expr).expect("bind"); + evaluator.evaluate(&bound).expect("evaluate") +} + +fn single_table(name: &str, columns: &[(&str, &str)], rows: Vec>) -> DataModel { + DataModel { + tables: vec![ModelTable { + name: name.into(), + columns: columns.iter().map(|(name, kind)| ModelColumn { name: (*name).into(), data_type: Some((*kind).into()) }).collect(), + rows, + }], + ..DataModel::default() + } +} + +#[test] +fn ragged_rows_keep_the_row_scan_semantics() { + // Row 0 only supplies A; the missing B cell is a row the columnar copy would blank-extend. + let model = + single_table("Sales", &[("A", "Int64"), ("B", "Int64")], vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2), Scalar::Integer(3)]]); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let storage = evaluator.storage().expect("the ragged model still materializes"); + assert!(!storage.is_faithful(), "a ragged row cannot round-trip"); + + let expr = parse_expression("SUM(Sales[B])").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + // `TableValue::column` skips a row shorter than the requested column, so only row 1 counts. + assert_eq!(evaluator.evaluate(&bound).expect("evaluate"), Scalar::Decimal(3.0)); + assert_eq!(eval(&model, "COUNTROWS(Sales)"), Scalar::Integer(2)); + assert!(evaluator.storage_stats().row_scan_fallbacks > 0, "{:?}", evaluator.storage_stats()); +} + +#[test] +fn promoted_columns_keep_the_row_scan_semantics() { + // Booleans mixed with an integer are promoted to dictionary-encoded text by the storage + // inference; DAX's SUM ignores logicals (only numbers are aggregated), so storage must not + // answer and the row-scan path must agree. + let model = single_table("Mixed", &[("Value", "Boolean")], vec![vec![Scalar::Boolean(true)], vec![Scalar::Integer(2)], vec![Scalar::Blank]]); + let evaluator = Evaluator::new(&model).expect("evaluator"); + assert!(!evaluator.storage().expect("storage").is_faithful()); + + let expr = parse_expression("SUM(Mixed[Value])").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate(&bound).expect("evaluate"), Scalar::Decimal(2.0)); + assert_eq!(eval(&model, "COUNT(Mixed[Value])"), Scalar::Integer(1), "COUNT ignores booleans"); + assert_eq!(eval(&model, "COUNTA(Mixed[Value])"), Scalar::Integer(2)); + assert!(evaluator.storage_stats().row_scan_fallbacks > 0, "{:?}", evaluator.storage_stats()); +} + +#[test] +fn unmaterializable_models_still_evaluate() { + // A relationship naming a missing table makes `ModelStorage::from_model` fail. That is not an + // evaluation error: the row-scan path is the documented fallback and the reason is reported. + let mut model = single_table("Sales", &[("Amount", "Int64")], vec![vec![Scalar::Integer(4)], vec![Scalar::Integer(6)]]); + model.relationships.push(Relationship { + from_table: "Sales".into(), + from_column: "Amount".into(), + to_table: "Ghost".into(), + to_column: "Amount".into(), + bidirectional: false, + inactive: false, + }); + let evaluator = Evaluator::new(&model).expect("evaluator still builds"); + assert!(evaluator.storage().is_none()); + assert_eq!(evaluator.storage_error(), Some(&StorageError::UnknownTable { table: "Ghost".into() })); + + let expr = parse_expression("SUM(Sales[Amount])").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate(&bound).expect("evaluate"), Scalar::Decimal(10.0)); + assert!(evaluator.storage_stats().row_scan_fallbacks > 0); +} + +#[test] +fn countblank_counts_empty_text_in_both_paths() { + // DAX COUNTBLANK counts an empty string as blank. The storage fast path reads that from the + // string dictionary, so pin it against the documented row-path rule. + let model = single_table( + "Notes", + &[("Text", "String")], + vec![vec![Scalar::String(String::new())], vec![Scalar::String("x".into())], vec![Scalar::Blank]], + ); + let evaluator = Evaluator::new(&model).expect("evaluator"); + assert!(evaluator.storage().expect("storage").is_faithful()); + assert_eq!(eval(&model, "COUNTBLANK(Notes[Text])"), Scalar::Integer(2)); + assert_eq!(eval(&model, "COUNTA(Notes[Text])"), Scalar::Integer(2)); + assert_eq!(eval(&model, "DISTINCTCOUNT(Notes[Text])"), Scalar::Integer(3)); +} + +#[test] +fn mixed_numeric_columns_promote_but_keep_their_sum() { + // Integers and decimals mix into one decimal column, which cannot round-trip. The sum is the + // same either way, so this pins the value while the fallback keeps the representation honest. + let model = single_table( + "Money", + &[("Amount", "Double")], + vec![vec![Scalar::Integer(1)], vec![Scalar::Decimal(0.5)], vec![Scalar::Blank], vec![Scalar::Integer(3)]], + ); + let evaluator = Evaluator::new(&model).expect("evaluator"); + assert!(!evaluator.storage().expect("storage").is_faithful()); + assert_eq!(eval(&model, "SUM(Money[Amount])"), Scalar::Decimal(4.5)); + assert_eq!(eval(&model, "COUNT(Money[Amount])"), Scalar::Integer(3)); + assert_eq!(eval(&model, "COUNTBLANK(Money[Amount])"), Scalar::Integer(1)); +} + +#[test] +fn pivot_over_a_non_faithful_model_groups_rows() { + // Row 1 has no Amount cell, so the model cannot be stored faithfully and the pivot must go + // back to grouping model rows. The blank amount makes the West cell BLANK, not zero. + let mut model = DataModel { + tables: vec![ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) }, + ], + rows: vec![vec![Scalar::String("East".into()), Scalar::Integer(10)], vec![Scalar::String("West".into())]], + }], + measures: vec![gridcraft_dax::Measure { + name: "Total".into(), + formula: "SUM(Sales[Amount])".into(), + table: Some("Sales".into()), + format: None, + expr: None, + }], + ..DataModel::default() + }; + model.parse_formulas().expect("model parses"); + + let pivot = gridcraft_dax::pivot_table::PivotTable::new("By region", "Total") + .with_row_fields(vec!["Sales[Region]".into()]) + .with_grand_totals(true) + .with_layout(gridcraft_dax::pivot_table::PivotLayout::Tabular); + let (table, stats) = pivot.render_with_stats(&model).expect("render"); + + assert_eq!(table.rows.len(), 3); + assert_eq!(table.rows[0], vec![Scalar::String("East".into()), Scalar::Decimal(10.0)]); + assert_eq!(table.rows[1], vec![Scalar::String("West".into()), Scalar::Blank]); + assert_eq!(table.rows[2], vec![Scalar::String("Grand Total".into()), Scalar::Decimal(10.0)]); + assert_eq!(stats.pivot_group_rows, 0, "grouping fell back to the model rows: {stats:?}"); + assert!(stats.row_scan_fallbacks > 0); +} diff --git a/crates/dax/tests/eval_storage_scale.rs b/crates/dax/tests/eval_storage_scale.rs new file mode 100644 index 000000000..cea35051c --- /dev/null +++ b/crates/dax/tests/eval_storage_scale.rs @@ -0,0 +1,202 @@ +//! Scale test: 100k rows through the columnar substrate. +//! +//! What is measured: +//! +//! * wall-clock time of `Evaluator::new` (one materialization), of `SUMX`/`COUNTROWS`/ +//! `DISTINCTCOUNT` and of a 8-group pivot with a grand total, printed with `--nocapture` and +//! asserted to stay under [`BUDGET`]; +//! * the storage counters of the same calls, which prove the numbers were computed from columns +//! and bound the work: a pivot cell may only touch rows of its own group plus one pass over the +//! source row ids, so `rows_from_storage` has to stay linear in the row count (an accidental +//! per-cell full scan of a 100k-row model across 100 groups would blow the budget and the +//! bound below). +//! +//! Peak memory is not sampled (it is not portable across the test hosts); the bound that matters +//! is structural: the model keeps one scalar per cell, storage adds one typed value plus one null +//! bit per cell, and no path clones model rows — `rows_from_storage` counts rows served from +//! columns, and the only `Vec>` materialized here is the pivot's own output table +//! (9 rows). +//! +//! This is an integration-test binary: it is never compiled for wasm, so reading the clock here +//! cannot hit the trap the workspace `disallowed_methods` lint guards against. +#![allow(clippy::disallowed_methods)] + +use std::time::{Duration, Instant}; + +use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable}; +use gridcraft_dax::pivot_table::{PivotLayout, PivotTable}; +use gridcraft_dax::value::Scalar; +use gridcraft_dax::{Binder, Evaluator, FilterContext, StorageStats, parse_expression}; + +const ROWS: usize = 100_000; +const REGIONS: [&str; 8] = ["East", "West", "North", "South", "Centre", "Coastal", "Inland", "Metro"]; +/// Generous upper bound: a debug build handles this fixture in well under a second on the +/// development machine, so 60 s only catches a pathological (quadratic or repeating-scan) change. +const BUDGET: Duration = Duration::from_secs(60); + +fn amount(row: usize) -> i64 { + (row % 1_000) as i64 +} + +fn region(row: usize) -> &'static str { + REGIONS[row % REGIONS.len()] +} + +fn product_key(row: usize) -> i64 { + (row % 50) as i64 + 1 +} + +fn model() -> DataModel { + let mut rows = Vec::with_capacity(ROWS); + for row in 0..ROWS { + rows.push(vec![ + Scalar::Integer(product_key(row)), + Scalar::String(region(row).into()), + Scalar::Integer(amount(row)), + Scalar::Integer((row % 7) as i64 + 1), + ]); + } + let mut model = DataModel { + tables: vec![ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) }, + ], + rows, + }], + relationships: Vec::new(), + measures: vec![ + Measure { name: "Total Amount".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }, + Measure { name: "Rows".into(), formula: "COUNTROWS(Sales)".into(), table: Some("Sales".into()), format: None, expr: None }, + Measure { + name: "Products".into(), + formula: "DISTINCTCOUNT(Sales[ProductKey])".into(), + table: Some("Sales".into()), + format: None, + expr: None, + }, + ], + }; + model.parse_formulas().expect("model parses"); + model +} + +fn evaluate(evaluator: &Evaluator<'_>, model: &DataModel, formula: &str) -> Scalar { + let expr = parse_expression(formula).expect("parse"); + let bound = Binder::new(model).bind_expression(&expr).expect("bind"); + evaluator.evaluate(&bound).expect("evaluate") +} + +#[test] +fn hundred_thousand_rows_evaluate_within_the_budget() { + let model = model(); + // Independent expectations from the generator, not from the DAX engine. + let mut per_region = vec![0i64; REGIONS.len()]; + let mut total = 0i64; + for row in 0..ROWS { + per_region[row % REGIONS.len()] += amount(row); + total += amount(row); + } + + let built = Instant::now(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let build_time = built.elapsed(); + let storage = evaluator.storage().expect("the generated model materializes"); + assert!(storage.is_faithful(), "the generated columns are homogeneous and rectangular"); + + let started = Instant::now(); + // sum of (row % 1000) over 100k rows = 100 blocks of 0..999 = 100 * 499_500. + assert_eq!(evaluate(&evaluator, &model, "SUMX(Sales, Sales[Amount])"), Scalar::Decimal(total as f64)); + let sum_time = started.elapsed(); + + let started = Instant::now(); + assert_eq!(evaluate(&evaluator, &model, "COUNTROWS(Sales)"), Scalar::Integer(ROWS as i64)); + let count_time = started.elapsed(); + + let started = Instant::now(); + assert_eq!(evaluate(&evaluator, &model, "DISTINCTCOUNT(Sales[ProductKey])"), Scalar::Integer(50)); + let distinct_time = started.elapsed(); + + let pivot = PivotTable::new("Sales by region", "Total Amount") + .with_row_fields(vec!["Sales[Region]".into()]) + .with_grand_totals(true) + .with_layout(PivotLayout::Tabular); + let started = Instant::now(); + let (table, stats) = pivot.render_with_stats(&model).expect("render"); + let pivot_time = started.elapsed(); + + // One row per region in ScalarKey order plus the grand total. + let mut sorted: Vec<(&str, i64)> = REGIONS.iter().copied().zip(per_region.iter().copied()).collect(); + sorted.sort_by(|left, right| left.0.cmp(right.0)); + let mut expected: Vec> = + sorted.iter().map(|(label, sum)| vec![Scalar::String((*label).into()), Scalar::Decimal(*sum as f64)]).collect(); + expected.push(vec![Scalar::String("Grand Total".into()), Scalar::Decimal(total as f64)]); + assert_eq!(table.rows, expected); + assert_eq!(table.rows.len(), REGIONS.len() + 1); + + let total_time = build_time + sum_time + count_time + distinct_time + pivot_time; + eprintln!( + "100k rows: build {build_time:?}, SUMX {sum_time:?}, COUNTROWS {count_time:?}, DISTINCTCOUNT {distinct_time:?}, pivot {pivot_time:?}, total {total_time:?}" + ); + // The pivot renders through its own evaluator, so read the two counter snapshots separately. + let direct = evaluator.storage_stats(); + eprintln!("counters for SUMX/COUNTROWS/DISTINCTCOUNT: {direct:?}"); + eprintln!("counters for the pivot render: {stats:?}"); + + // Every one of these calls was answered from columns, not from a row scan. + assert!(direct.iterators > 0, "SUMX went through storage: {direct:?}"); + assert!(direct.count_rows > 0, "COUNTROWS went through storage: {direct:?}"); + assert!(direct.aggregates > 0, "DISTINCTCOUNT went through storage: {direct:?}"); + assert!(stats.aggregates > 0, "every pivot cell went through storage: {stats:?}"); + assert_eq!(stats.pivot_group_rows, ROWS as u64, "grouping read every source row once"); + assert_eq!(evaluator.storage_stats().row_scan_fallbacks, 0); + + // Linear work per cell: 8 groups + the grand total + the grouping pass stay within a few + // passes of the 100k rows (an accidental per-cell full scan of the model would not). + assert!(stats.rows_from_storage < 20 * ROWS as u64, "rows served from columns must stay linear: {stats:?}"); + assert!(total_time < BUDGET, "100k rows took {total_time:?}, over the {BUDGET:?} budget"); +} + +/// The filters path at scale: a single-group pivot restricted to one region. +#[test] +fn filtered_pivot_at_scale_counts_one_region() { + let model = model(); + let mut expected = 0i64; + for row in (0..ROWS).filter(|row| row % REGIONS.len() == 0) { + expected += amount(row); + } + let pivot = PivotTable::new("East only", "Total Amount") + .with_row_fields(vec!["Sales[Region]".into()]) + .with_filter(gridcraft_dax::pivot_table::PivotFilter::new("Sales[Region]", [Scalar::String("East".into())])) + .with_grand_totals(true) + .with_layout(PivotLayout::Tabular); + let started = Instant::now(); + let (table, stats) = pivot.render_with_stats(&model).expect("render"); + let elapsed = started.elapsed(); + eprintln!("100k rows, filtered pivot: {elapsed:?}, counters {stats:?}"); + + assert_eq!(table.rows.len(), 2, "the East leaf plus the grand total"); + assert_eq!(table.rows[0], vec![Scalar::String("East".into()), Scalar::Decimal(expected as f64)]); + assert_eq!(table.rows[1], vec![Scalar::String("Grand Total".into()), Scalar::Decimal(expected as f64)]); + assert_eq!(stats.pivot_group_rows, ROWS as u64 / REGIONS.len() as u64); + assert!(elapsed < BUDGET); +} + +/// Every measure evaluates at scale through storage, without a per-measure rebuild. +#[test] +fn measures_at_scale_share_one_substrate() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let mut total = 0i64; + for row in 0..ROWS { + total += amount(row); + } + assert_eq!(evaluator.evaluate_measure("Total Amount", FilterContext::default()).expect("measure"), Scalar::Decimal(total as f64)); + assert_eq!(evaluator.evaluate_measure("Rows", FilterContext::default()).expect("measure"), Scalar::Integer(ROWS as i64)); + assert_eq!(evaluator.evaluate_measure("Products", FilterContext::default()).expect("measure"), Scalar::Integer(50)); + let stats: StorageStats = evaluator.storage_stats(); + assert!(stats.aggregates >= 2 && stats.count_rows == 1, "{stats:?}"); +} diff --git a/crates/dax/tests/eval_storage_wiring.rs b/crates/dax/tests/eval_storage_wiring.rs new file mode 100644 index 000000000..28b0b2b33 --- /dev/null +++ b/crates/dax/tests/eval_storage_wiring.rs @@ -0,0 +1,203 @@ +//! Wiring test: evaluation really reads the columnar `ModelStorage`, not just the model rows. +//! +//! `Evaluator::storage_stats` counts calls *served by* storage. Each test takes a snapshot, runs +//! one formula, and asserts the counter that formula must move went up; `row_scan_fallbacks` +//! covers the opposite direction. A formula that quietly fell back to the row scan leaves its +//! counter at zero, so these assertions fail if the wiring is ever removed. + +use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship}; +use gridcraft_dax::pivot_table::{PivotLayout, PivotTable}; +use gridcraft_dax::value::Scalar; +use gridcraft_dax::{Binder, Evaluator, FilterContext, StorageStats, parse_expression}; + +fn model() -> DataModel { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Product".into(), + columns: vec![ + ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Category".into(), data_type: Some("String".into()) }, + ModelColumn { name: "UnitPrice".into(), data_type: Some("Currency".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(1), Scalar::String("Hardware".into()), Scalar::Currency(200_000)], + vec![Scalar::Integer(2), Scalar::String("Tools".into()), Scalar::Currency(50_000)], + ], + }, + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(1), Scalar::String("East".into()), Scalar::Integer(10), Scalar::Integer(2)], + vec![Scalar::Integer(1), Scalar::String("West".into()), Scalar::Integer(20), Scalar::Integer(3)], + vec![Scalar::Integer(2), Scalar::String("East".into()), Scalar::Integer(5), Scalar::Integer(1)], + ], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "ProductKey".into(), + to_table: "Product".into(), + to_column: "ProductKey".into(), + bidirectional: false, + inactive: false, + }], + measures: vec![ + Measure { name: "Total Amount".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }, + Measure { name: "Rows".into(), formula: "COUNTROWS(Sales)".into(), table: Some("Sales".into()), format: None, expr: None }, + Measure { + name: "Extended".into(), + formula: "SUMX(Sales, Sales[Quantity] * RELATED(Product[UnitPrice]))".into(), + table: Some("Sales".into()), + format: None, + expr: None, + }, + ], + }; + model.parse_formulas().expect("model parses"); + model +} + +fn evaluate(evaluator: &Evaluator<'_>, model: &DataModel, formula: &str) -> (Scalar, StorageStats) { + let expr = parse_expression(formula).expect("parse"); + let bound = Binder::new(model).bind_expression(&expr).expect("bind"); + let value = evaluator.evaluate(&bound).expect("evaluate"); + (value, evaluator.storage_stats()) +} + +fn evaluate_table(evaluator: &Evaluator<'_>, model: &DataModel, formula: &str) -> (gridcraft_dax::TableValue, StorageStats) { + let expr = parse_expression(formula).expect("parse"); + let bound = Binder::new(model).bind_expression(&expr).expect("bind"); + let table = evaluator.evaluate_table(&bound).expect("table"); + (table, evaluator.storage_stats()) +} + +#[test] +fn sumx_runs_over_a_storage_column() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + assert!(evaluator.storage().expect("storage").is_faithful()); + + let (value, stats) = evaluate(&evaluator, &model, "SUMX(Sales, Sales[Amount])"); + assert_eq!(value, Scalar::Decimal(35.0)); + assert_eq!(stats.iterators, 1, "SUMX over a plain column is one storage iterator: {stats:?}"); + assert_eq!(stats.aggregates, 1); + assert_eq!(stats.rows_from_storage, 3); + assert_eq!(stats.row_scan_fallbacks, 0); +} + +#[test] +fn countrows_uses_the_filtered_row_id_set() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let (value, stats) = evaluate(&evaluator, &model, "COUNTROWS(Sales)"); + assert_eq!(value, Scalar::Integer(3)); + assert_eq!(stats.count_rows, 1, "{stats:?}"); + assert_eq!(stats.rows_from_storage, 3); + + // A filter becomes a storage column scan, and the count follows from the row ids. + let mut filtered = FilterContext::default(); + filtered.set(1, 1, [gridcraft_dax::ScalarKey::String("East".into())]); + let expr = parse_expression("COUNTROWS(Sales)").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate_with(&bound, filtered).expect("evaluate"), Scalar::Integer(2)); + let stats = evaluator.storage_stats(); + assert_eq!(stats.count_rows, 2); + assert_eq!(stats.filter_scans, 1, "{stats:?}"); +} + +#[test] +fn related_resolves_through_the_relationship_index() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + // 20*2 + 20*3 + 5*1 = 40 + 60 + 5 = 105; the derived expression keeps the iterator row-based, + // but every RELATED call is an index probe. + let (value, stats) = evaluate(&evaluator, &model, "SUMX(Sales, Sales[Quantity] * RELATED(Product[UnitPrice]))"); + assert_eq!(value, Scalar::Decimal(105.0)); + assert_eq!(stats.related, 3, "one index lookup per row: {stats:?}"); + assert_eq!(stats.relationship_lookups, 3); + assert_eq!(stats.iterators, 0, "a derived expression cannot use the plain-column iterator"); +} + +#[test] +fn relatedtable_resolves_through_the_relationship_index() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + // Product 1 has two sales rows, product 2 has one: 2 + 1 = 3. + let (value, stats) = evaluate(&evaluator, &model, "SUMX(Product, COUNTROWS(RELATEDTABLE(Sales)))"); + assert_eq!(value, Scalar::Decimal(3.0)); + assert_eq!(stats.related_table, 2, "one join per product row: {stats:?}"); + + // Filtered related rows: West only, so product 1 has one row and product 2 none. + let mut filtered = FilterContext::default(); + filtered.set(1, 1, [gridcraft_dax::ScalarKey::String("West".into())]); + let expr = parse_expression("SUMX(Product, COUNTROWS(RELATEDTABLE(Sales)))").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate_with(&bound, filtered).expect("evaluate"), Scalar::Decimal(1.0)); +} + +#[test] +fn values_and_distinct_dedupe_through_storage() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let (table, stats) = evaluate_table(&evaluator, &model, "VALUES(Sales[Region])"); + assert_eq!(table.rows, vec![vec![Scalar::String("East".into())], vec![Scalar::String("West".into())]]); + assert_eq!(stats.distinct_values, 1, "{stats:?}"); + assert_eq!(stats.rows_from_storage, 3); + + let (distinct, stats) = evaluate_table(&evaluator, &model, "DISTINCT(Sales[Region])"); + assert_eq!(distinct.rows, table.rows); + assert_eq!(stats.distinct_values, 2); +} + +#[test] +fn filter_propagation_uses_the_relationship_index() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + // Hardware products are only product 1, so sales rows 1 and 2: 10 + 20 = 30. + let (value, stats) = evaluate(&evaluator, &model, "CALCULATE(SUM(Sales[Amount]), Product[Category] = \"Hardware\")"); + assert_eq!(value, Scalar::Decimal(30.0)); + assert!(stats.relationship_lookups > 0, "propagation must probe the index: {stats:?}"); + assert_eq!(stats.aggregates, 1); +} + +#[test] +fn pivot_cells_and_grouping_are_served_by_storage() { + let model = model(); + let pivot = PivotTable::new("Sales by region", "Total Amount") + .with_row_fields(vec!["Sales[Region]".into()]) + .with_grand_totals(true) + .with_layout(PivotLayout::Tabular); + let (table, stats) = pivot.render_with_stats(&model).expect("render"); + + assert_eq!(table.rows.len(), 3); + assert_eq!(table.rows[0], vec![Scalar::String("East".into()), Scalar::Decimal(15.0)]); + assert_eq!(table.rows[1], vec![Scalar::String("West".into()), Scalar::Decimal(20.0)]); + assert_eq!(table.rows[2], vec![Scalar::String("Grand Total".into()), Scalar::Decimal(35.0)]); + + assert_eq!(stats.pivot_group_rows, 3, "grouping reads the source rows from columns: {stats:?}"); + assert!(stats.aggregates > 0, "every cell is a storage aggregate: {stats:?}"); + assert_eq!(stats.row_scan_fallbacks, 0); +} + +#[test] +fn measures_share_one_substrate_across_evaluations() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + assert_eq!(evaluator.evaluate_measure("Total Amount", FilterContext::default()).expect("measure"), Scalar::Decimal(35.0)); + assert_eq!(evaluator.evaluate_measure("Rows", FilterContext::default()).expect("measure"), Scalar::Integer(3)); + assert_eq!(evaluator.evaluate_measure("Extended", FilterContext::default()).expect("measure"), Scalar::Decimal(105.0)); + let stats = evaluator.storage_stats(); + assert_eq!(stats.aggregates, 1); + assert_eq!(stats.count_rows, 1); + assert_eq!(stats.related, 3); + // The substrate is built once in `Evaluator::new` and shared: its table ids are the model + // positions, so repeated evaluation never rebuilds it. + assert_eq!(evaluator.storage().expect("storage").total_rows(), 5); +} diff --git a/crates/dax/tests/evaluator.rs b/crates/dax/tests/evaluator.rs new file mode 100644 index 000000000..c331b1c69 --- /dev/null +++ b/crates/dax/tests/evaluator.rs @@ -0,0 +1,541 @@ +//! Core evaluator tests over an in-memory model. + +use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship}; +use gridcraft_dax::value::{Scalar, TableValue}; +use gridcraft_dax::{Binder, Evaluator, FilterContext, parse_expression}; + +fn model() -> DataModel { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) }, + ], + rows: vec![ + vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::Integer(2), Scalar::Boolean(true)], + vec![Scalar::String("West".into()), Scalar::Integer(20), Scalar::Integer(3), Scalar::Boolean(false)], + vec![Scalar::String("East".into()), Scalar::Integer(30), Scalar::Integer(4), Scalar::Boolean(true)], + ], + }, + ModelTable { name: "Date".into(), columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }], rows: vec![] }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "Region".into(), + to_table: "Date".into(), + to_column: "Date".into(), + bidirectional: false, + inactive: false, + }], + measures: vec![ + Measure { name: "Total Sales".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }, + Measure { + name: "East Sales".into(), + formula: "CALCULATE([Total Sales], Sales[Region] = \"East\")".into(), + table: Some("Sales".into()), + format: None, + expr: None, + }, + Measure { name: "Double Sales".into(), formula: "[Total Sales] * 2".into(), table: Some("Sales".into()), format: None, expr: None }, + ], + }; + model.parse_formulas().expect("model parses"); + model +} + +fn eval(src: &str) -> Scalar { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression(src).expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + evaluator.evaluate(&bound).expect("evaluate") +} + +fn eval_table(src: &str) -> TableValue { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression(src).expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + evaluator.evaluate_table(&bound).expect("table") +} + +#[test] +fn aggregates_and_measures() { + assert_eq!(eval("SUM(Sales[Amount])"), Scalar::Decimal(60.0)); + assert_eq!(eval("AVERAGE(Sales[Amount])"), Scalar::Decimal(20.0)); + assert_eq!(eval("COUNTROWS(Sales)"), Scalar::Integer(3)); + assert_eq!(eval("SUMX(Sales, Sales[Amount] * 2)"), Scalar::Decimal(120.0)); + assert_eq!(eval("[Total Sales]"), Scalar::Decimal(60.0)); + assert_eq!(eval("[East Sales]"), Scalar::Decimal(40.0)); + assert_eq!(eval("[Double Sales]"), Scalar::Decimal(120.0)); + assert_eq!(eval("CALCULATE([Total Sales], Sales[Region] = \"West\")"), Scalar::Decimal(20.0)); +} + +#[test] +fn logical_and_scalar_functions() { + assert_eq!(eval("IF([Total Sales] > 50, \"big\", \"small\")"), Scalar::String("big".into())); + assert_eq!(eval("SWITCH(2, 1, \"one\", 2, \"two\", \"other\")"), Scalar::String("two".into())); + assert_eq!(eval("COALESCE(BLANK(), 3)"), Scalar::Integer(3)); + assert_eq!(eval("LEFT(\"abcd\", 2)"), Scalar::String("ab".into())); + assert_eq!(eval("ROUND(1.234, 2)"), Scalar::Decimal(1.23)); + assert_eq!(eval("DATE(2024, 1, 2)"), Scalar::DateTime(45293.0)); + assert_eq!(eval("YEAR(DATE(2024, 1, 2))"), Scalar::Integer(2024)); + assert_eq!(eval("ISBLANK(BLANK())"), Scalar::Boolean(true)); +} + +#[test] +fn tables_filters_and_values() { + let filtered = eval_table("FILTER(Sales, Sales[Amount] > 10)"); + assert_eq!(filtered.rows.len(), 2); + let values = eval_table("VALUES(Sales[Region])"); + assert_eq!(values.rows.len(), 2); +} + +#[test] +fn documented_keyword_arguments_bind() { + let model = model(); + let binder = Binder::new(&model); + for src in ["DATEADD('Date'[Date], -1, MONTH)", "CONVERT(1, INTEGER)"] { + let expr = parse_expression(src).expect("parse"); + binder.bind_expression(&expr).expect("bind keyword argument"); + } +} + +#[test] +fn filter_context_can_be_supplied() { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression("[Total Sales]").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + let mut filters = FilterContext::default(); + filters.set(0, 0, [gridcraft_dax::ScalarKey::String("East".into())]); + assert_eq!(evaluator.evaluate_with(&bound, filters).expect("eval"), Scalar::Decimal(40.0)); +} + +#[test] +fn pivot_groups_and_evaluates_measures() { + let model = model(); + let fields = gridcraft_dax::pivot_fields(&model, &["Sales[Region]".into()]).expect("fields"); + let table = gridcraft_dax::pivot(&model, "Total Sales", &fields).expect("pivot"); + assert_eq!(table.rows.len(), 2); + assert_eq!(table.rows[0][0], Scalar::String("East".into())); + assert_eq!(table.rows[0][1], Scalar::Decimal(40.0)); + assert_eq!(table.rows[1][0], Scalar::String("West".into())); + assert_eq!(table.rows[1][1], Scalar::Decimal(20.0)); +} + +#[test] +fn iterators_resolve_rows_of_filtered_tables() { + // The frame must carry the row values, not the position in the filtered table. + assert_eq!(eval("SUMX(FILTER(Sales, Sales[Region] = \"West\"), Sales[Amount])"), Scalar::Decimal(20.0)); + // Context transition inside an iterator over a filtered table. + assert_eq!(eval("SUMX(FILTER(Sales, Sales[Amount] > 10), [Total Sales])"), Scalar::Decimal(50.0)); +} + +#[test] +fn calculate_accepts_filter_table_arguments() { + assert_eq!(eval("CALCULATE([Total Sales], FILTER(Sales, Sales[Amount] > 10))"), Scalar::Decimal(50.0)); + assert_eq!(eval("CALCULATE([Total Sales], Sales[Amount] >= 20)"), Scalar::Decimal(50.0)); + assert_eq!(eval("CALCULATE([Total Sales], 20 <= Sales[Amount])"), Scalar::Decimal(50.0)); + assert_eq!(eval("CALCULATE([Total Sales], Sales[Amount] < 20)"), Scalar::Decimal(10.0)); + assert_eq!(eval("CALCULATE([Total Sales], KEEPFILTERS(Sales[Region] = \"East\"))"), Scalar::Decimal(40.0)); +} + +#[test] +fn cyclic_measures_are_rejected_before_evaluation() { + let mut model = model(); + model.measures.push(Measure { name: "Cycle A".into(), formula: "[Cycle B] + 1".into(), table: Some("Sales".into()), format: None, expr: None }); + model.measures.push(Measure { name: "Cycle B".into(), formula: "[Cycle A] + 1".into(), table: Some("Sales".into()), format: None, expr: None }); + model.parse_formulas().expect("model parses"); + let error = match Evaluator::new(&model) { + Ok(_) => panic!("cyclic measures must be rejected"), + Err(error) => error, + }; + assert!(error.message.contains("Cycle"), "{error:?}"); +} + +#[test] +fn bidirectional_filters_do_not_recurse() { + let mut model = model(); + model.tables.push(ModelTable { + name: "Products".into(), + columns: vec![ModelColumn { name: "Region".into(), data_type: Some("String".into()) }], + rows: vec![vec![Scalar::String("East".into())], vec![Scalar::String("West".into())]], + }); + model.relationships.push(Relationship { + from_table: "Sales".into(), + from_column: "Region".into(), + to_table: "Products".into(), + to_column: "Region".into(), + bidirectional: true, + inactive: false, + }); + model.parse_formulas().expect("model parses"); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression("CALCULATE(SUM(Sales[Amount]), Products[Region] = \"East\")").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate(&bound).expect("bidirectional filter"), Scalar::Decimal(40.0)); + + model.relationships.last_mut().expect("relationship").inactive = true; + let evaluator = Evaluator::new(&model).expect("evaluator"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate(&bound).expect("inactive relationship is ignored"), Scalar::Decimal(60.0)); +} + +#[test] +fn relatedtable_returns_rows_from_the_many_side() { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ModelColumn { name: "Product".into(), data_type: Some("String".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(10), Scalar::String("A".into())], + vec![Scalar::Integer(20), Scalar::String("A".into())], + vec![Scalar::Integer(30), Scalar::String("B".into())], + ], + }, + ModelTable { + name: "Products".into(), + columns: vec![ModelColumn { name: "Product".into(), data_type: Some("String".into()) }], + rows: vec![vec![Scalar::String("A".into())], vec![Scalar::String("B".into())]], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "Product".into(), + to_table: "Products".into(), + to_column: "Product".into(), + bidirectional: false, + inactive: false, + }], + measures: Vec::new(), + }; + model.parse_formulas().expect("model parses"); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression("SUMX(Products, COUNTROWS(RELATEDTABLE(Sales)))").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate(&bound).expect("relatedtable"), Scalar::Decimal(3.0)); +} + +#[test] +fn calculate_performs_context_transition() { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ModelColumn { name: "Product".into(), data_type: Some("String".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(10), Scalar::String("A".into())], + vec![Scalar::Integer(20), Scalar::String("A".into())], + vec![Scalar::Integer(30), Scalar::String("B".into())], + ], + }, + ModelTable { + name: "Products".into(), + columns: vec![ModelColumn { name: "Product".into(), data_type: Some("String".into()) }], + rows: vec![vec![Scalar::String("A".into())], vec![Scalar::String("B".into())]], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "Product".into(), + to_table: "Products".into(), + to_column: "Product".into(), + bidirectional: false, + inactive: false, + }], + measures: Vec::new(), + }; + model.parse_formulas().expect("model parses"); + let evaluator = Evaluator::new(&model).expect("evaluator"); + // An explicit `CALCULATE` in a row context transitions that row, the way a measure + // reference does: A reports its own 30 and B its 30, not the 60 grand total. + for (formula, expected) in [("SUMX(Products, CALCULATE(SUM(Sales[Amount])))", 60.0), ("SUMX(Sales, CALCULATE(SUM(Sales[Amount])))", 60.0)] { + let expr = parse_expression(formula).expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate(&bound).expect("calculate"), Scalar::Decimal(expected), "{formula}"); + } + let expr = parse_expression("ADDCOLUMNS(Products, \"Total\", CALCULATE(SUM(Sales[Amount])))").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + let table = evaluator.evaluate_table(&bound).expect("addcolumns"); + let totals: Vec = table.rows.iter().map(|row| row[1].clone()).collect(); + assert_eq!(totals, vec![Scalar::Decimal(30.0), Scalar::Decimal(30.0)], "each row reports its own product, not the total"); +} + +#[test] +fn filters_propagate_across_several_relationships() { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ModelColumn { name: "Product".into(), data_type: Some("String".into()) }, + ], + rows: vec![vec![Scalar::Integer(10), Scalar::String("A".into())], vec![Scalar::Integer(20), Scalar::String("B".into())]], + }, + ModelTable { + name: "Products".into(), + columns: vec![ + ModelColumn { name: "Product".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Category".into(), data_type: Some("String".into()) }, + ], + rows: vec![ + vec![Scalar::String("A".into()), Scalar::String("East".into())], + vec![Scalar::String("B".into()), Scalar::String("West".into())], + ], + }, + ModelTable { + name: "Categories".into(), + columns: vec![ + ModelColumn { name: "Category".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Name".into(), data_type: Some("String".into()) }, + ], + rows: vec![ + vec![Scalar::String("East".into()), Scalar::String("Group East".into())], + vec![Scalar::String("West".into()), Scalar::String("Group West".into())], + ], + }, + ], + relationships: vec![ + Relationship { + from_table: "Sales".into(), + from_column: "Product".into(), + to_table: "Products".into(), + to_column: "Product".into(), + bidirectional: false, + inactive: false, + }, + Relationship { + from_table: "Products".into(), + from_column: "Category".into(), + to_table: "Categories".into(), + to_column: "Category".into(), + bidirectional: false, + inactive: false, + }, + ], + measures: vec![Measure { name: "Total".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }], + }; + model.parse_formulas().expect("model parses"); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression("CALCULATE([Total], Categories[Name] = \"Group East\")").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate(&bound).expect("multi-hop filter"), Scalar::Decimal(10.0)); +} + +#[test] +fn bidirectional_filters_keep_orphan_rows() { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ModelColumn { name: "Product".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(10), Scalar::String("A".into()), Scalar::String("East".into())], + // No matching Products row: a bidirectional relationship must keep it. + vec![Scalar::Integer(20), Scalar::String("Orphan".into()), Scalar::String("East".into())], + ], + }, + ModelTable { + name: "Products".into(), + columns: vec![ModelColumn { name: "Product".into(), data_type: Some("String".into()) }], + rows: vec![vec![Scalar::String("A".into())]], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "Product".into(), + to_table: "Products".into(), + to_column: "Product".into(), + bidirectional: true, + inactive: false, + }], + measures: vec![Measure { name: "Total".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }], + }; + model.parse_formulas().expect("model parses"); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression("CALCULATE([Total], Sales[Region] = \"East\")").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert_eq!(evaluator.evaluate(&bound).expect("bidirectional filter"), Scalar::Decimal(30.0)); +} + +#[test] +fn userelationship_selects_the_matching_relationship_by_column() { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ModelColumn { name: "OrderDate".into(), data_type: Some("DateTime".into()) }, + ModelColumn { name: "ShipDate".into(), data_type: Some("DateTime".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(10), Scalar::DateTime(45292.0), Scalar::DateTime(45293.0)], + vec![Scalar::Integer(20), Scalar::DateTime(45293.0), Scalar::DateTime(45292.0)], + ], + }, + ModelTable { + name: "Date".into(), + columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }], + rows: vec![vec![Scalar::DateTime(45292.0)], vec![Scalar::DateTime(45293.0)]], + }, + ], + relationships: vec![ + Relationship { + from_table: "Sales".into(), + from_column: "OrderDate".into(), + to_table: "Date".into(), + to_column: "Date".into(), + bidirectional: false, + inactive: false, + }, + Relationship { + from_table: "Sales".into(), + from_column: "ShipDate".into(), + to_table: "Date".into(), + to_column: "Date".into(), + bidirectional: false, + inactive: true, + }, + ], + measures: vec![Measure { name: "Total".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }], + }; + model.parse_formulas().expect("model parses"); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let evaluate = |src: &str| { + let expr = parse_expression(src).expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + evaluator.evaluate(&bound).expect("evaluate") + }; + // The active OrderDate relationship sees the Jan 2 order row. + assert_eq!(evaluate("CALCULATE([Total], Date[Date] = DATE(2024,1,2))"), Scalar::Decimal(20.0)); + // USERELATIONSHIP picks ShipDate even though OrderDate is the first relationship in the model. + assert_eq!(evaluate("CALCULATE([Total], USERELATIONSHIP(Sales[ShipDate], Date[Date]), Date[Date] = DATE(2024,1,2))"), Scalar::Decimal(10.0)); + assert_eq!(evaluate("CALCULATE([Total], USERELATIONSHIP(Sales[ShipDate], Date[Date]), Date[Date] = DATE(2024,1,1))"), Scalar::Decimal(20.0)); + // CROSSFILTER accepts both documented spellings and leaves the active relationship in place. + assert_eq!(evaluate("CALCULATE([Total], CROSSFILTER(Sales[OrderDate], Date[Date], OneWay))"), Scalar::Decimal(30.0)); + assert_eq!(evaluate("CALCULATE([Total], CROSSFILTER(Sales[OrderDate], Date[Date], BOTH))"), Scalar::Decimal(30.0)); +} + +#[test] +fn calculate_filters_replace_the_target_column_and_map_by_name() { + // The outer filter on Region must not suppress the candidates for the CALCULATE filter. + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression("CALCULATE([Total Sales], Sales[Region] = \"East\")").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + let mut filters = FilterContext::default(); + filters.set(0, 0, [gridcraft_dax::ScalarKey::String("West".into())]); + assert_eq!(evaluator.evaluate_with(&bound, filters).expect("evaluate"), Scalar::Decimal(40.0)); + + // VALUES(Sales[Amount]) exposes one column at position 0; it must filter Amount, not Region. + assert_eq!(eval("CALCULATE([Total Sales], VALUES(Sales[Amount]))"), Scalar::Decimal(60.0)); +} + +#[test] +fn relationship_modifiers_apply_inside_calculate() { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ModelColumn { name: "Key".into(), data_type: Some("Int64".into()) }, + ], + rows: vec![vec![Scalar::Integer(10), Scalar::Integer(1)], vec![Scalar::Integer(20), Scalar::Integer(2)]], + }, + ModelTable { + name: "Dim".into(), + columns: vec![ + ModelColumn { name: "Key".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Name".into(), data_type: Some("String".into()) }, + ], + rows: vec![vec![Scalar::Integer(1), Scalar::String("A".into())], vec![Scalar::Integer(2), Scalar::String("B".into())]], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "Key".into(), + to_table: "Dim".into(), + to_column: "Key".into(), + bidirectional: false, + inactive: false, + }], + measures: Vec::new(), + }; + model.parse_formulas().expect("model parses"); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let evaluate = |src: &str| { + let expr = parse_expression(src).expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + evaluator.evaluate(&bound).expect("evaluate") + }; + // A Sales filter reaches Dim only when CROSSFILTER makes the relationship bidirectional. + assert_eq!(evaluate("CALCULATE(COUNTROWS(Dim), Sales[Key] = 1)"), Scalar::Integer(2)); + assert_eq!(evaluate("CALCULATE(COUNTROWS(Dim), Sales[Key] = 1, CROSSFILTER(Sales[Key], Dim[Key], BOTH))"), Scalar::Integer(1)); + // The modifier itself is not a scalar. + let expr = parse_expression("USERELATIONSHIP(Sales[Key], Dim[Key])").expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert!(evaluator.evaluate(&bound).is_err(), "a modifier cannot be a standalone scalar"); +} + +#[test] +fn unbounded_scalar_functions_return_errors() { + for formula in ["FACT(171)", "REPT(\"x\", 100000)"] { + let model = model(); + let evaluator = Evaluator::new(&model).expect("evaluator"); + let expr = parse_expression(formula).expect("parse"); + let bound = Binder::new(&model).bind_expression(&expr).expect("bind"); + assert!(evaluator.evaluate(&bound).is_err(), "{formula} must fail"); + } +} + +#[test] +fn scalar_json_round_trip_preserves_variants() { + for value in [Scalar::Currency(123_456), Scalar::DateTime(45293.5), Scalar::Integer(7), Scalar::Decimal(1.5), Scalar::Blank] { + let json = serde_json::to_value(&value).expect("serialize"); + let back: Scalar = serde_json::from_value(json.clone()).expect("deserialize"); + assert_eq!(back, value, "round trip through {json}"); + } +} + +#[test] +fn scalar_keys_sort_numerically() { + let mut keys: Vec = + [-2.5, -1.0, 0.0, 1.0, 2.5].into_iter().map(|value| gridcraft_dax::ScalarKey::from(&Scalar::Decimal(value))).collect(); + keys.sort(); + let back: Vec = keys.iter().map(|key| key.to_scalar().to_number().unwrap_or_default()).collect(); + assert_eq!(back, vec![-2.5, -1.0, 0.0, 1.0, 2.5]); + assert_eq!(gridcraft_dax::ScalarKey::from(&Scalar::Decimal(-0.0)), gridcraft_dax::ScalarKey::from(&Scalar::Decimal(0.0))); +} + +#[test] +fn pivot_cross_puts_column_groups_in_columns() { + let model = model(); + let rows = gridcraft_dax::pivot_fields(&model, &["Sales[Region]".into()]).expect("rows"); + let columns = gridcraft_dax::pivot_fields(&model, &["Sales[Flag]".into()]).expect("columns"); + let table = gridcraft_dax::pivot_cross(&model, "Total Sales", &rows, &columns).expect("pivot"); + assert_eq!(table.columns.len(), 3); + assert_eq!(table.rows.len(), 2); + assert_eq!(table.rows[0][0], Scalar::String("East".into())); + // FALSE sorts before TRUE; East has TRUE rows only (10 + 30). + assert_eq!(table.rows[0][1], Scalar::Blank); + assert_eq!(table.rows[0][2], Scalar::Decimal(40.0)); +} diff --git a/crates/dax/tests/storage.rs b/crates/dax/tests/storage.rs new file mode 100644 index 000000000..b26faa76f --- /dev/null +++ b/crates/dax/tests/storage.rs @@ -0,0 +1,432 @@ +//! Columnar storage tests over the evaluator's in-memory model shape. + +use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable, Relationship}; +use gridcraft_dax::storage::{Aggregate, Bitmap, ColumnData, ColumnKind, ColumnStorage, ModelStorage, StorageError, TableStorage}; +use gridcraft_dax::value::{Scalar, ScalarKey}; + +fn sample_model() -> DataModel { + DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Price".into(), data_type: Some("Currency".into()) }, + ModelColumn { name: "Closed".into(), data_type: Some("DateTime".into()) }, + ModelColumn { name: "Returned".into(), data_type: Some("Boolean".into()) }, + ModelColumn { name: "Note".into(), data_type: Some("String".into()) }, + ], + rows: vec![ + vec![ + Scalar::Integer(2), + Scalar::String("East".into()), + Scalar::Integer(10), + Scalar::Currency(12500), + Scalar::DateTime(45000.0), + Scalar::Boolean(true), + Scalar::Blank, + ], + vec![ + Scalar::Integer(1), + Scalar::String("West".into()), + Scalar::Integer(20), + Scalar::Currency(5000), + Scalar::DateTime(45001.5), + Scalar::Boolean(false), + Scalar::Blank, + ], + vec![ + Scalar::Integer(2), + Scalar::String("East".into()), + Scalar::Integer(30), + Scalar::Currency(7500), + Scalar::DateTime(45002.0), + Scalar::Boolean(true), + Scalar::Blank, + ], + vec![Scalar::Integer(3), Scalar::Blank, Scalar::Blank, Scalar::Blank, Scalar::Blank, Scalar::Blank, Scalar::Blank], + vec![ + Scalar::Integer(99), + Scalar::String("North".into()), + Scalar::Integer(40), + Scalar::Currency(2500), + Scalar::DateTime(45003.25), + Scalar::Boolean(false), + Scalar::Blank, + ], + vec![ + Scalar::Blank, + Scalar::String("East".into()), + Scalar::Integer(5), + Scalar::Currency(1000), + Scalar::DateTime(45004.0), + Scalar::Boolean(true), + Scalar::Blank, + ], + ], + }, + ModelTable { + name: "Product".into(), + columns: vec![ + ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Name".into(), data_type: Some("String".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(1), Scalar::String("Widget".into())], + vec![Scalar::Integer(2), Scalar::String("Gadget".into())], + vec![Scalar::Integer(2), Scalar::String("Gadget".into())], + vec![Scalar::Integer(3), Scalar::String("Gizmo".into())], + ], + }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "ProductKey".into(), + to_table: "Product".into(), + to_column: "ProductKey".into(), + bidirectional: false, + inactive: false, + }], + measures: vec![], + } +} + +fn storage() -> ModelStorage { + match ModelStorage::from_model(&sample_model()) { + Ok(storage) => storage, + Err(error) => panic!("sample model builds: {error}"), + } +} + +fn sales(storage: &ModelStorage) -> &TableStorage { + match storage.table_by_name("Sales") { + Some(table) => table, + None => panic!("Sales table exists"), + } +} + +fn column_index(table: &TableStorage, name: &str) -> usize { + match table.column_index(name) { + Some(index) => index, + None => panic!("column `{name}` exists"), + } +} + +#[test] +fn builds_tables_with_stable_ids_and_inferred_types() { + let storage = storage(); + assert_eq!(storage.tables().len(), 2); + assert_eq!(storage.table_index("sales"), Some(0)); + assert_eq!(storage.table_index("PRODUCT"), Some(1)); + assert_eq!(storage.table(2), None); + assert_eq!(storage.table_by_name("missing"), None); + assert_eq!(storage.total_rows(), 10); + + let sales = sales(&storage); + assert_eq!(sales.name(), "Sales"); + assert_eq!(sales.row_count(), 6); + assert_eq!(sales.columns().len(), 7); + assert_eq!(sales.column_index("region"), Some(1)); + assert_eq!(sales.column_index("Missing"), None); + + let kinds: Vec = sales.columns().iter().map(|column| column.kind()).collect(); + assert_eq!( + kinds, + vec![ + ColumnKind::Integer, + ColumnKind::String, + ColumnKind::Integer, + ColumnKind::Currency, + ColumnKind::DateTime, + ColumnKind::Boolean, + ColumnKind::Blank, + ] + ); + assert_eq!(sales.columns()[0].len(), 6); + assert!(sales.columns()[0].kind().is_numeric()); + assert!(!sales.columns()[1].kind().is_numeric()); + + let product = match storage.table(1) { + Some(table) => table, + None => panic!("Product table exists"), + }; + assert_eq!(product.column_by_name("name").map(ColumnStorage::kind), Some(ColumnKind::String)); + + // Table ids and column ids follow the model, so lookups agree with the metadata layer. + let model = sample_model(); + assert_eq!(model.table_index("Sales"), Some(0)); + assert_eq!(model.column_index(0, "Amount"), Some(2)); + assert_eq!(storage.column_index(0, "Amount"), Some(2)); + assert_eq!(storage.column(0, 2).map(ColumnStorage::name), Some("Amount")); + assert_eq!(storage.column(9, 0), None); + assert_eq!(storage.value(0, 2, 0), Some(Scalar::Integer(10))); + assert_eq!(storage.value(0, 2, 6), None); + assert_eq!(storage.value(0, 2, 3), Some(Scalar::Blank)); +} + +#[test] +fn string_columns_are_dictionary_encoded() { + let storage = storage(); + let sales = sales(&storage); + let region = match sales.column(1).map(ColumnStorage::data) { + Some(ColumnData::String { dictionary, codes, nulls }) => (dictionary.clone(), codes.clone(), nulls.clone()), + other => panic!("Region should be dictionary encoded, got {other:?}"), + }; + let (dictionary, codes, nulls) = region; + assert_eq!(dictionary, vec!["East".to_string(), "West".to_string(), "North".to_string()]); + assert_eq!(codes, vec![0, 1, 0, 0, 2, 0]); + assert_eq!(nulls.count_ones(), 1); + assert!(nulls.get(3)); + assert!(!nulls.get(0)); + + // Every row reads back exactly, including the blank placeholder code. + let expected = [ + Scalar::String("East".into()), + Scalar::String("West".into()), + Scalar::String("East".into()), + Scalar::Blank, + Scalar::String("North".into()), + Scalar::String("East".into()), + ]; + for (row, value) in expected.iter().enumerate() { + assert_eq!(sales.value_by_name("Region", row).as_ref(), Some(value)); + } + assert_eq!(sales.column(1).map(|column| column.data().value(6)), Some(None)); +} + +#[test] +fn filters_by_value_set_including_blanks_and_duplicates() { + let storage = storage(); + let sales = sales(&storage); + let region = column_index(sales, "Region"); + assert_eq!( + sales.filter_rows(region, &[ScalarKey::String("East".into()), ScalarKey::Blank, ScalarKey::String("East".into())]), + Ok(vec![0, 2, 3, 5]) + ); + assert_eq!(sales.filter_rows(region, &[ScalarKey::String("West".into())]), Ok(vec![1])); + assert_eq!(sales.filter_rows(region, &[ScalarKey::String("east".into())]), Ok(vec![])); + assert_eq!(sales.filter_rows(region, &[]), Ok(vec![])); + + let product_key = column_index(sales, "ProductKey"); + assert_eq!(sales.filter_rows(product_key, &[ScalarKey::Integer(2)]), Ok(vec![0, 2])); + assert_eq!(sales.filter_rows(product_key, &[ScalarKey::Blank]), Ok(vec![5])); + assert_eq!(sales.filter_rows(product_key, &[ScalarKey::Integer(2), ScalarKey::Blank]), Ok(vec![0, 2, 5])); + + // All-blank columns match only the blank key; the empty string is a different value. + let note = column_index(sales, "Note"); + assert_eq!(sales.filter_rows(note, &[ScalarKey::Blank]), Ok(vec![0, 1, 2, 3, 4, 5])); + assert_eq!(sales.filter_rows(note, &[ScalarKey::String(String::new())]), Ok(vec![])); + + assert_eq!(sales.filter_rows(99, &[ScalarKey::Blank]), Err(StorageError::ColumnOutOfRange { table: "Sales".into(), index: 99 })); +} + +#[test] +fn aggregates_skip_blanks_but_count_distinct_blanks() { + let storage = storage(); + let sales = sales(&storage); + let amount = column_index(sales, "Amount"); + let all_rows: Vec = (0..sales.row_count()).collect(); + + assert_eq!(sales.sum(amount, &all_rows), Ok(Scalar::Integer(105))); + assert_eq!(sales.count(amount, &all_rows), Ok(Scalar::Integer(5))); + assert_eq!(sales.distinct_count(amount, &all_rows), Ok(Scalar::Integer(6))); + assert_eq!(sales.min(amount, &all_rows), Ok(Scalar::Integer(5))); + assert_eq!(sales.max(amount, &all_rows), Ok(Scalar::Integer(40))); + assert_eq!(sales.aggregate(amount, &all_rows, Aggregate::Sum), Ok(Scalar::Integer(105))); + assert_eq!(sales.aggregate(amount, &all_rows, Aggregate::Count), Ok(Scalar::Integer(5))); + assert_eq!(sales.aggregate(amount, &all_rows, Aggregate::DistinctCount), Ok(Scalar::Integer(6))); + assert_eq!(sales.aggregate(amount, &all_rows, Aggregate::Min), Ok(Scalar::Integer(5))); + assert_eq!(sales.aggregate(amount, &all_rows, Aggregate::Max), Ok(Scalar::Integer(40))); + + // A filtered subset, plus empty-selection blank semantics. + assert_eq!(sales.sum(amount, &[0, 1]), Ok(Scalar::Integer(30))); + assert_eq!(sales.sum(amount, &[]), Ok(Scalar::Blank)); + assert_eq!(sales.count(amount, &[]), Ok(Scalar::Integer(0))); + assert_eq!(sales.distinct_count(amount, &[]), Ok(Scalar::Integer(0))); + assert_eq!(sales.min(amount, &[]), Ok(Scalar::Blank)); + assert_eq!(sales.max(amount, &[]), Ok(Scalar::Blank)); + + // Currency keeps its scaled representation. + let price = column_index(sales, "Price"); + assert_eq!(sales.sum(price, &all_rows), Ok(Scalar::Currency(28_500))); + + // DateTime sums as a decimal serial; min/max keep the DateTime type. + let closed = column_index(sales, "Closed"); + assert_eq!(sales.sum(closed, &all_rows), Ok(Scalar::Decimal(45000.0 + 45001.5 + 45002.0 + 45003.25 + 45004.0))); + assert_eq!(sales.min(closed, &all_rows), Ok(Scalar::DateTime(45000.0))); + assert_eq!(sales.max(closed, &all_rows), Ok(Scalar::DateTime(45004.0))); + + assert_eq!(sales.sum(column_index(sales, "Region"), &all_rows), Err(StorageError::NotNumeric { table: "Sales".into(), column: "Region".into() })); + assert_eq!(sales.sum(amount, &[6]), Err(StorageError::RowOutOfRange { table: "Sales".into(), column: "Amount".into(), row: 6, row_count: 6 })); +} + +#[test] +fn blank_columns_handle_every_aggregate() { + let storage = storage(); + let sales = sales(&storage); + let note = column_index(sales, "Note"); + let all_rows: Vec = (0..sales.row_count()).collect(); + let data = match sales.column(note) { + Some(column) => column.data(), + None => panic!("Note column exists"), + }; + assert_eq!(data.kind(), ColumnKind::Blank); + assert_eq!(data.len(), 6); + assert_eq!(data.null_bitmap(), None); + assert_eq!(data.blank_count(), 6); + assert_eq!(data.is_blank_at(0), Some(true)); + assert_eq!(data.is_blank_at(6), None); + assert_eq!(data.value(0), Some(Scalar::Blank)); + + assert_eq!(sales.sum(note, &all_rows), Ok(Scalar::Blank)); + assert_eq!(sales.count(note, &all_rows), Ok(Scalar::Integer(0))); + assert_eq!(sales.distinct_count(note, &all_rows), Ok(Scalar::Integer(1))); + assert_eq!(sales.min(note, &all_rows), Ok(Scalar::Blank)); + assert_eq!(sales.max(note, &all_rows), Ok(Scalar::Blank)); +} + +#[test] +fn relationship_indexes_map_keys_to_row_ids() { + let storage = storage(); + assert_eq!(storage.relationships().len(), 1); + let relationship = match storage.relationships().first() { + Some(relationship) => relationship, + None => panic!("relationship exists"), + }; + assert_eq!((relationship.from_table, relationship.from_column), (0, 0)); + assert_eq!((relationship.to_table, relationship.to_column), (1, 0)); + assert!(!relationship.bidirectional); + assert!(!relationship.inactive); + + // Duplicate keys on both sides keep every row id. + assert_eq!(relationship.rows_from(&ScalarKey::Integer(2)), &[0, 2]); + assert_eq!(relationship.rows_from(&ScalarKey::Integer(1)), &[1]); + assert_eq!(relationship.rows_from(&ScalarKey::Integer(3)), &[3]); + assert_eq!(relationship.rows_from(&ScalarKey::Integer(99)), &[4]); + assert_eq!(relationship.rows_from(&ScalarKey::Blank), &[5]); + assert!(relationship.rows_from(&ScalarKey::Integer(1000)).is_empty()); + + assert_eq!(relationship.rows_to(&ScalarKey::Integer(2)), &[1, 2]); + assert_eq!(relationship.rows_to(&ScalarKey::Integer(1)), &[0]); + assert_eq!(relationship.rows_to(&ScalarKey::Integer(3)), &[3]); + assert!(relationship.rows_to(&ScalarKey::Integer(99)).is_empty()); + assert!(relationship.rows_to(&ScalarKey::Blank).is_empty()); + + assert_eq!(relationship.from_key_count(), 5); + assert_eq!(relationship.to_key_count(), 3); + assert_eq!(storage.relationships_from(0).count(), 1); + assert_eq!(storage.relationships_to(1).count(), 1); + assert_eq!(storage.relationships_from(1).count(), 0); + assert!(storage.relationship("sales", "productkey", "product", "productkey").is_some()); + assert!(storage.relationship("Sales", "Region", "Product", "ProductKey").is_none()); + + // The index joins to a filtered key: product 2 selects Sales rows 0 and 2. + let sales = sales(&storage); + let amount = column_index(sales, "Amount"); + assert_eq!(sales.sum(amount, relationship.rows_from(&ScalarKey::Integer(2))), Ok(Scalar::Integer(40))); +} + +#[test] +fn values_round_trip_for_every_representation() { + let columns = vec![ + "Integer".to_string(), + "Currency".to_string(), + "Decimal".to_string(), + "DateTime".to_string(), + "Boolean".to_string(), + "String".to_string(), + "AllBlank".to_string(), + ]; + let rows = vec![ + vec![ + Scalar::Integer(7), + Scalar::Currency(12345), + Scalar::Decimal(1.5), + Scalar::DateTime(45000.25), + Scalar::Boolean(true), + Scalar::String("x".into()), + Scalar::Blank, + ], + vec![Scalar::Blank, Scalar::Blank, Scalar::Blank, Scalar::Blank, Scalar::Blank, Scalar::Blank, Scalar::Blank], + vec![ + Scalar::Integer(-3), + Scalar::Currency(-500), + Scalar::Decimal(-2.25), + Scalar::DateTime(45001.0), + Scalar::Boolean(false), + Scalar::String("y".into()), + Scalar::Blank, + ], + ]; + let table = match TableStorage::from_rows("Mixed", columns, rows.clone()) { + Ok(table) => table, + Err(error) => panic!("mixed table builds: {error}"), + }; + let expected_kinds = vec![ + ColumnKind::Integer, + ColumnKind::Currency, + ColumnKind::Decimal, + ColumnKind::DateTime, + ColumnKind::Boolean, + ColumnKind::String, + ColumnKind::Blank, + ]; + for (column, kind) in table.columns().iter().zip(expected_kinds) { + assert_eq!(column.kind(), kind, "column {}", column.name()); + } + for (row, values) in rows.iter().enumerate() { + for (column, expected) in values.iter().enumerate() { + assert_eq!(table.value(column, row).as_ref(), Some(expected), "row {row} column {column}"); + } + } + + // Ragged rows are blank-extended, and extra cells are ignored. + let ragged = match TableStorage::from_rows( + "Ragged", + vec!["A".to_string(), "B".to_string()], + vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2), Scalar::String("two".into()), Scalar::Integer(99)]], + ) { + Ok(table) => table, + Err(error) => panic!("ragged table builds: {error}"), + }; + assert_eq!(ragged.row_count(), 2); + assert_eq!(ragged.value_by_name("B", 0), Some(Scalar::Blank)); + assert_eq!(ragged.value_by_name("B", 1), Some(Scalar::String("two".into()))); + let a = match ragged.column_by_name("A").map(ColumnStorage::data) { + Some(ColumnData::Integer { values, .. }) => values.clone(), + other => panic!("A should be integer, got {other:?}"), + }; + assert_eq!(a, vec![1, 2]); +} + +#[test] +fn construction_and_lookup_failures_are_bounded() { + assert_eq!( + TableStorage::from_rows("Dup", vec!["A".to_string(), "a".to_string()], vec![vec![Scalar::Integer(1), Scalar::Integer(2)]]), + Err(StorageError::DuplicateColumn { table: "Dup".into(), column: "a".into() }) + ); + + let column = ColumnStorage::new("A", ColumnData::Integer { values: vec![1], nulls: Bitmap::new(1) }); + assert_eq!( + TableStorage::new("Short", 2, vec![column]), + Err(StorageError::ColumnLengthMismatch { table: "Short".into(), column: "A".into(), column_len: 1, row_count: 2 }) + ); + + let mut invalid = sample_model(); + invalid.relationships.push(Relationship { + from_table: "Sales".into(), + from_column: "ProductKey".into(), + to_table: "Missing".into(), + to_column: "ProductKey".into(), + bidirectional: false, + inactive: false, + }); + assert_eq!(ModelStorage::from_model(&invalid), Err(StorageError::UnknownTable { table: "Missing".into() })); + + let mut duplicate = sample_model(); + let first = duplicate.tables[0].clone(); + duplicate.tables.push(first); + assert_eq!(ModelStorage::from_model(&duplicate), Err(StorageError::DuplicateTable { table: "Sales".into() })); +} diff --git a/crates/dax/tests/storage_compression_encoding.rs b/crates/dax/tests/storage_compression_encoding.rs new file mode 100644 index 000000000..7b5950cd4 --- /dev/null +++ b/crates/dax/tests/storage_compression_encoding.rs @@ -0,0 +1,268 @@ +//! Compression round-trip and vectorized-scan tests for the columnar store. +//! +//! The fixture is the shape compression exists for: a 100k-row fact-like table whose keys repeat +//! in long blocks, whose labels have few distinct values, and whose measures are high entropy. The +//! tests prove three things: +//! +//! * the encoding selection is the one documented (`RleInteger`/`RleCurrency` for long runs, +//! `PackedString` for few labels, plain vectors for high-entropy columns); +//! * decoding is exact — every value reads back, [`ModelStorage::is_faithful`] stays true, and every +//! aggregate equals the value computed from the generator, including `sum_batch`/`sum_batches` +//! and the allocation-free `for_each_value` scan; +//! * the same aggregate answers whether or not a selection is sorted, has duplicates, or is empty. + +use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable}; +use gridcraft_dax::storage::{ColumnData, ColumnKind, ColumnStorage, ModelStorage, SCAN_BATCH_ROWS, ValueRef}; +use gridcraft_dax::value::Scalar; + +const ROWS: usize = 100_000; +const REGIONS: [&str; 8] = ["East", "West", "North", "South", "Centre", "Coastal", "Inland", "Metro"]; + +fn block(row: usize) -> i64 { + (row / 1_000) as i64 +} + +fn region(row: usize) -> &'static str { + REGIONS[row % REGIONS.len()] +} + +fn price(row: usize) -> i64 { + (row / 1_000) as i64 * 10_000 +} + +fn model() -> DataModel { + let mut rows = Vec::with_capacity(ROWS); + for row in 0..ROWS { + rows.push(vec![ + Scalar::Integer(block(row)), + Scalar::String(region(row).into()), + Scalar::Integer(row as i64), + Scalar::Currency(price(row)), + Scalar::String("Constant".into()), + Scalar::Boolean(row % 2 == 0), + ]); + } + DataModel { + tables: vec![ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Block".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Price".into(), data_type: Some("Currency".into()) }, + ModelColumn { name: "Tag".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) }, + ], + rows, + }], + ..DataModel::default() + } +} + +fn column_data(storage: &ModelStorage, name: &str) -> ColumnData { + let table = storage.table(0).expect("table"); + table.column_by_name(name).expect("column").data().clone() +} + +#[test] +fn low_cardinality_and_run_columns_compress_and_high_entropy_columns_do_not() { + let model = model(); + let storage = ModelStorage::from_model(&model).expect("storage"); + assert!(storage.is_faithful(), "compression must stay lossless"); + + assert!(matches!(column_data(&storage, "Block"), ColumnData::RleInteger { .. }), "1k-row runs should run-length encode"); + assert!(matches!(column_data(&storage, "Price"), ColumnData::RleCurrency { .. }), "currency runs should run-length encode"); + assert!(matches!(column_data(&storage, "Region"), ColumnData::PackedString { .. }), "8 labels should bit-pack"); + assert!(matches!(column_data(&storage, "Tag"), ColumnData::PackedString { .. }), "a constant label should bit-pack"); + assert!(matches!(column_data(&storage, "Amount"), ColumnData::Integer { .. }), "high-entropy integers stay plain"); + assert!(matches!(column_data(&storage, "Flag"), ColumnData::Boolean { .. }), "alternating booleans have no runs to save"); + + let table = storage.table(0).expect("table"); + // A constant column needs zero bits per code. + let tag = table.column_by_name("Tag").expect("Tag"); + if let ColumnData::PackedString { packed, .. } = tag.data() { + assert_eq!(packed.bits_per_code(), 0); + assert_eq!(packed.bytes(), 0); + } else { + panic!("Tag should be packed, got {:?}", tag.data()); + } + let region = table.column_by_name("Region").expect("Region"); + if let ColumnData::PackedString { packed, .. } = region.data() { + assert_eq!(packed.bits_per_code(), 3, "8 labels need 3 bits"); + } else { + panic!("Region should be packed, got {:?}", region.data()); + } +} + +#[test] +fn every_value_decodes_exactly_including_blanks() { + let mut model = model(); + // Add blanks so the bitmap path is exercised under compression. + for row in (0..ROWS).step_by(7) { + if let Some(cells) = model.tables[0].rows.get_mut(row) { + cells[0] = Scalar::Blank; + cells[2] = Scalar::Blank; + cells[3] = Scalar::Blank; + } + } + let storage = ModelStorage::from_model(&model).expect("storage"); + assert!(storage.is_faithful()); + let table = storage.table(0).expect("table"); + for row in 0..ROWS { + let expected = model.tables[0].rows.get(row).expect("row"); + for column in 0..expected.len() { + assert_eq!(table.value(column, row).as_ref(), expected.get(column), "cell ({column}, {row})"); + } + } + // Blanks really are masked, not zeroed. + assert_eq!(table.value_by_name("Block", 0), Some(Scalar::Blank)); + assert_eq!(table.value_by_name("Block", 1), Some(Scalar::Integer(0))); +} + +#[test] +fn aggregates_match_the_generator_for_run_and_packed_columns() { + let storage = ModelStorage::from_model(&model()).expect("storage"); + let table = storage.table(0).expect("table"); + let all: Vec = (0..ROWS).collect(); + + let block_sum: i64 = (0..ROWS).map(block).sum(); + assert_eq!(table.sum(0, &all), Ok(Scalar::Integer(block_sum))); + let amount_sum: i64 = (0..ROWS).map(|row| row as i64).sum(); + assert_eq!(table.sum(2, &all), Ok(Scalar::Integer(amount_sum))); + let price_sum: i64 = (0..ROWS).map(price).sum(); + assert_eq!(table.sum(3, &all), Ok(Scalar::Currency(price_sum))); + + assert_eq!(table.count(0, &all), Ok(Scalar::Integer(ROWS as i64))); + assert_eq!(table.distinct_count(1, &all), Ok(Scalar::Integer(8))); + assert_eq!(table.distinct_count(4, &all), Ok(Scalar::Integer(1))); + assert_eq!(table.count_blank(0, &all), Ok(Scalar::Integer(0))); + assert_eq!(table.min(0, &all), Ok(Scalar::Integer(0))); + assert_eq!(table.max(0, &all), Ok(Scalar::Integer(block(ROWS - 1)))); + + let mut expected_regions: Vec = REGIONS.iter().map(|name| Scalar::String((*name).into())).collect(); + let distinct = table.distinct_values(1, &all).expect("distinct"); + let mut distinct_sorted: Vec = distinct.clone(); + expected_regions.sort_by_key(Scalar::to_text); + distinct_sorted.sort_by_key(Scalar::to_text); + assert_eq!(distinct_sorted, expected_regions); + + // numeric_values length and a few observations. + let values = table.numeric_values(0, &all).expect("numeric values"); + assert_eq!(values.len(), ROWS); + assert_eq!(values.first().copied(), Some(0.0)); + assert_eq!(values.last().copied(), Some(block(ROWS - 1) as f64)); + assert!(table.numeric_values(1, &all).expect("text values").is_empty()); +} + +#[test] +fn subset_sums_are_order_independent_and_match_scalar_arithmetic() { + let storage = ModelStorage::from_model(&model()).expect("storage"); + let table = storage.table(0).expect("table"); + + let unsorted = vec![99_999, 0, 500, 500, 999, 99_998, 3, 3, 3]; + let expected: i64 = unsorted.iter().map(|row| block(*row)).sum(); + assert!(unsorted.windows(2).any(|pair| pair[0] > pair[1]), "selection is deliberately unsorted"); + assert_eq!(table.sum(0, &unsorted), Ok(Scalar::Integer(expected))); + assert_eq!(table.sum_batch(0, &unsorted), Ok(Scalar::Integer(expected))); + + // An empty selection and a selection of blanks are BLANK. + assert_eq!(table.sum(0, &[]), Ok(Scalar::Blank)); + assert_eq!(table.sum_batch(0, &[]), Ok(Scalar::Blank)); + + let batches: Vec<&[usize]> = vec![&[0, 1, 2], &[99_999], &[], &[500, 500]]; + let totals = table.sum_batches(0, &batches).expect("batches"); + assert_eq!(totals, vec![Scalar::Integer(0), Scalar::Integer(block(99_999)), Scalar::Blank, Scalar::Integer(0),]); + + // A scan block boundary must not change the answer. + let crossing: Vec = (SCAN_BATCH_ROWS - 3..=SCAN_BATCH_ROWS + 3).collect(); + let expected: i64 = crossing.iter().map(|row| block(*row)).sum(); + assert_eq!(table.sum(0, &crossing), Ok(Scalar::Integer(expected))); +} + +#[test] +fn for_each_value_scans_without_materializing_scalars() { + let storage = ModelStorage::from_model(&model()).expect("storage"); + let table = storage.table(0).expect("table"); + let rows = vec![0, 1, 7, 8, 99_999]; + + let mut seen: Vec<(usize, String)> = Vec::new(); + table + .for_each_value(1, &rows, |row, value| { + let text = match value { + ValueRef::Text(text) => text.to_string(), + other => panic!("expected text, got {other:?}"), + }; + seen.push((row, text)); + }) + .expect("scan"); + assert_eq!(seen, rows.iter().map(|row| (*row, region(*row).to_string())).collect::>()); + + // Integer and boolean views keep their exact representation. + let mut integers = Vec::new(); + table + .for_each_value(0, &rows, |_, value| match value { + ValueRef::Integer(cell) => integers.push(cell), + other => panic!("expected integer, got {other:?}"), + }) + .expect("scan"); + assert_eq!(integers, rows.iter().map(|row| block(*row)).collect::>()); + + let mut booleans = Vec::new(); + table + .for_each_value(5, &rows, |_, value| match value { + ValueRef::Boolean(cell) => booleans.push(cell), + other => panic!("expected boolean, got {other:?}"), + }) + .expect("scan"); + assert_eq!(booleans, rows.iter().map(|row| row % 2 == 0).collect::>()); + + // Out-of-range row ids are rejected before any value is visited. + assert!(table.for_each_value(0, &[ROWS], |_, _| panic!("nothing should be visited")).is_err()); +} + +#[test] +fn filters_and_distinct_paths_read_packed_codes() { + let storage = ModelStorage::from_model(&model()).expect("storage"); + let table = storage.table(0).expect("table"); + let wanted = vec![gridcraft_dax::value::ScalarKey::String("West".into())]; + let rows = table.filter_rows(1, &wanted).expect("filter"); + assert_eq!(rows.len(), ROWS / REGIONS.len()); + assert!(rows.iter().all(|row| region(*row) == "West")); + + for column in 0..table.columns().len() { + let storage = table.column(column).expect("column"); + if storage.kind() != ColumnKind::String { + continue; + } + assert!(matches!(storage.data(), ColumnData::PackedString { .. }), "column {column} should be packed: {:?}", storage.data()); + } +} + +#[test] +fn short_columns_keep_the_plain_representation() { + // Below the minimum saving a plain vector wins: no fixture with a handful of rows changes shape. + let model = DataModel { + tables: vec![ModelTable { + name: "Tiny".into(), + columns: vec![ + ModelColumn { name: "Key".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Label".into(), data_type: Some("String".into()) }, + ], + rows: vec![ + vec![Scalar::Integer(1), Scalar::String("East".into())], + vec![Scalar::Integer(1), Scalar::String("West".into())], + vec![Scalar::Integer(1), Scalar::String("East".into())], + vec![Scalar::Integer(1), Scalar::String("North".into())], + vec![Scalar::Integer(1), Scalar::String("East".into())], + vec![Scalar::Integer(1), Scalar::String("West".into())], + ], + }], + ..DataModel::default() + }; + let storage = ModelStorage::from_model(&model).expect("storage"); + let table = storage.table(0).expect("table"); + assert!(matches!(table.column(0).map(ColumnStorage::data), Some(ColumnData::Integer { .. }))); + assert!(matches!(table.column(1).map(ColumnStorage::data), Some(ColumnData::String { .. }))); + // The stored codes remain the plain vector the model produced. + assert_eq!(table.column(1).map(ColumnStorage::data).map(ColumnData::codes), Some(&[0_u32, 1, 0, 2, 0, 1][..])); +} diff --git a/crates/dax/tests/storage_compression_footprint.rs b/crates/dax/tests/storage_compression_footprint.rs new file mode 100644 index 000000000..94d246ca8 --- /dev/null +++ b/crates/dax/tests/storage_compression_footprint.rs @@ -0,0 +1,144 @@ +//! Memory-accounting tests: per-column encoded versus logical bytes and the model total. +//! +//! The store exposes [`gridcraft_dax::storage::StorageFootprint`] (via `ModelStorage::footprint`) +//! with one [`gridcraft_dax::storage::ColumnFootprint`] per column. These tests pin the numbers that +//! the encoding decisions are supposed to produce: +//! +//! * a 100k-row run-length column is at least an order of magnitude smaller than its full-width +//! payload; +//! * a 100k-row low-cardinality text column is several times smaller; +//! * a constant text column stores no code bytes at all; +//! * a high-entropy column never grows beyond its payload plus its null bitmap; +//! * the totals are the sums of the parts, and the ratio is the model-level claim. + +use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable}; +use gridcraft_dax::storage::{ColumnKind, ModelStorage, StorageFootprint}; +use gridcraft_dax::value::Scalar; + +const ROWS: usize = 100_000; +const REGIONS: [&str; 8] = ["East", "West", "North", "South", "Centre", "Coastal", "Inland", "Metro"]; + +fn model() -> DataModel { + let mut rows = Vec::with_capacity(ROWS); + for row in 0..ROWS { + rows.push(vec![ + Scalar::Integer((row / 1_000) as i64), + Scalar::String(REGIONS[row % REGIONS.len()].into()), + Scalar::Integer(row as i64), + Scalar::Currency((row / 1_000) as i64 * 10_000), + Scalar::String("Constant".into()), + ]); + } + DataModel { + tables: vec![ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Block".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) }, + ModelColumn { name: "Price".into(), data_type: Some("Currency".into()) }, + ModelColumn { name: "Tag".into(), data_type: Some("String".into()) }, + ], + rows, + }], + ..DataModel::default() + } +} + +fn find<'a>(footprint: &'a StorageFootprint, name: &str) -> &'a gridcraft_dax::ColumnFootprint { + let table = footprint.tables.first().expect("one table"); + assert_eq!(table.table, "Sales"); + let index = match name { + "Block" => 0, + "Region" => 1, + "Amount" => 2, + "Price" => 3, + "Tag" => 4, + other => panic!("unknown column {other}"), + }; + table.columns.get(index).expect("column footprint") +} + +#[test] +fn run_length_and_packed_columns_account_for_far_less_than_their_logical_size() { + let storage = ModelStorage::from_model(&model()).expect("storage"); + let footprint = storage.footprint(); + + let block = find(&footprint, "Block"); + assert_eq!(block.kind, ColumnKind::Integer); + assert_eq!(block.rows, ROWS); + assert_eq!(block.logical_bytes, ROWS * 8, "one i64 slot per row"); + // 100 runs: 100 values + 101 offsets = 1608 bytes, plus the 12.5 kB null bitmap. + assert_eq!(block.encoded_bytes, 100 * 8 + 101 * 8 + ROWS.div_ceil(64) * 8); + assert!(block.encoded_bytes * 10 < block.logical_bytes, "run-length encoding must be >10x smaller"); + assert_eq!(block.saved_bytes(), block.logical_bytes - block.encoded_bytes); + + let price = find(&footprint, "Price"); + assert_eq!(price.kind, ColumnKind::Currency); + assert_eq!(price.logical_bytes, ROWS * 8); + assert!(price.encoded_bytes * 10 < price.logical_bytes); + + let region = find(&footprint, "Region"); + assert_eq!(region.kind, ColumnKind::String); + let dictionary_bytes: usize = REGIONS.iter().map(|name| name.len()).sum(); + assert_eq!(region.logical_bytes, ROWS * 4 + dictionary_bytes, "four bytes per plain code plus the labels"); + assert_eq!(region.encoded_bytes, (ROWS * 3).div_ceil(64) * 8 + dictionary_bytes + ROWS.div_ceil(64) * 8); + assert!(region.encoded_bytes * 4 < region.logical_bytes, "3-bit codes must be several times smaller"); + assert!(region.ratio() < 0.2); +} + +#[test] +fn a_constant_column_costs_no_code_bytes() { + let storage = ModelStorage::from_model(&model()).expect("storage"); + let footprint = storage.footprint(); + let tag = find(&footprint, "Tag"); + let dictionary_bytes = "Constant".len(); + assert_eq!(tag.logical_bytes, ROWS * 4 + dictionary_bytes); + // Zero bits per code: only the labels and the null bitmap remain. + assert_eq!(tag.encoded_bytes, dictionary_bytes + ROWS.div_ceil(64) * 8); + assert!(tag.ratio() < 0.05, "a constant column stores the label once: {}", tag.ratio()); + assert!(tag.saved_bytes() > ROWS * 3); +} + +#[test] +fn a_high_entropy_column_does_not_grow_beyond_its_payload_and_bitmap() { + let storage = ModelStorage::from_model(&model()).expect("storage"); + let footprint = storage.footprint(); + let amount = find(&footprint, "Amount"); + assert_eq!(amount.kind, ColumnKind::Integer); + assert_eq!(amount.logical_bytes, ROWS * 8); + assert_eq!(amount.encoded_bytes, ROWS * 8 + ROWS.div_ceil(64) * 8, "plain values plus the null bitmap"); + // The stated bound: a high-entropy column never exceeds its logical payload plus its bitmap. + assert!(amount.encoded_bytes <= amount.logical_bytes + ROWS.div_ceil(8) + 64); + assert_eq!(amount.saved_bytes(), 0); + assert!(amount.ratio() > 1.0, "the null bitmap is the only overhead"); +} + +#[test] +fn totals_are_the_sum_of_the_parts() { + let storage = ModelStorage::from_model(&model()).expect("storage"); + let footprint = storage.footprint(); + let table = footprint.tables.first().expect("one table"); + let summed_logical: usize = table.columns.iter().map(|column| column.logical_bytes).sum(); + let summed_encoded: usize = table.columns.iter().map(|column| column.encoded_bytes).sum(); + assert_eq!(table.logical_bytes(), summed_logical); + assert_eq!(table.encoded_bytes(), summed_encoded); + assert_eq!(footprint.logical_bytes(), summed_logical); + assert_eq!(footprint.encoded_bytes(), summed_encoded); + assert_eq!(footprint.saved_bytes(), summed_logical - summed_encoded); + + // Five columns, each reported once with its table name. + let columns: Vec<(&str, usize)> = footprint.columns().map(|(table, index, _)| (table, index)).collect(); + assert_eq!(columns, vec![("Sales", 0), ("Sales", 1), ("Sales", 2), ("Sales", 3), ("Sales", 4)]); + + // The model total saves the run-length and packed columns even with the plain ones counted. + assert!(footprint.ratio() < 0.6, "measured ratio {}", footprint.ratio()); + assert!(footprint.saved_bytes() > ROWS * 8, "at least one full-width column's worth of savings"); +} + +#[test] +fn accounting_is_reproducible() { + let first = ModelStorage::from_model(&model()).expect("storage").footprint(); + let second = ModelStorage::from_model(&model()).expect("storage").footprint(); + assert_eq!(first, second); +}