diff --git a/docs/compatibility/directed-relationships.md b/docs/compatibility/directed-relationships.md index 6ba49f2aa..71e30f474 100644 --- a/docs/compatibility/directed-relationships.md +++ b/docs/compatibility/directed-relationships.md @@ -17,6 +17,14 @@ An automatic query anchor must reach the selected models through permitted paths; an explicitly chosen invalid anchor is rejected. The same direction restriction applies to junction paths and nested relationship roles. +The automatic anchor is the model that owns the selected metrics. When that model +cannot reach every selected model through permitted paths, the first selected +model that can do so anchors the query instead. A metric on `customers` grouped +by an `orders` dimension therefore anchors on `orders` here, because nothing may +traverse from `customers` to `orders`. If another permitted route exists, such as +`customers -> accounts -> orders`, the metric owner anchors and that route is the +one joined; name the anchor with an Explore to choose the population yourself. + Aggregate deduplication still accounts for repeated target rows. Queries with metrics at different grains use preaggregation when either a many-to-one or one-to-many path can repeat a metric's rows, including forward-only paths. diff --git a/docs/native-format.md b/docs/native-format.md index 0fcd9aec3..278d30588 100644 --- a/docs/native-format.md +++ b/docs/native-format.md @@ -515,6 +515,72 @@ Relationship types: - `one_to_many` - `many_to_many` +### Which rows a joined query keeps + +The model that owns the selected metrics is the preserved side of the join. Models +that only supply dimensions are `LEFT JOIN`ed onto it, across every hop: + +- A metric row whose key is `NULL` or matches no dimension row is counted in a + `NULL` dimension group, so a breakdown adds up to the ungrouped total. +- A dimension row that no metric row references is not a group. `orders.revenue` + by `customers.region` lists no region without orders. +- A filter or segment on a dimension model's column keeps only metric rows that + have a matching dimension row, so it removes the `NULL` group. That includes + `IS NULL` predicates; filter on the metric model's own key column to inspect + unmatched rows. +- The same holds when the metric sits on the "one" side: `customers.customer_count` + by `orders.status` keeps every customer once, with customers without orders in a + `NULL` status group. + +Metrics from several models keep each model's own rows, so their groups are the +union of those populations. A query with dimensions and no metric starts from its +first dimension's model. + +To list every dimension member, including those without metric rows, either query +through an Explore whose base `model` is the dimension model, or also select a +metric owned by that model: + +```yaml +models: + - name: customers + table: customers + primary_key: id + dimensions: + - name: region + type: categorical + metrics: + - name: customer_count + agg: count + - name: orders + table: orders + primary_key: id + relationships: + - name: customers + type: many_to_one + foreign_key: customer_id + metrics: + - name: revenue + agg: sum + sql: amount + - name: order_count + agg: count + +explores: + - name: by_customer + model: customers +``` + +```bash +# Every customer region; regions without orders have NULL revenue and a zero count. +sidemantic query --explore by_customer --metric orders.revenue --metric orders.order_count --dimension region +# Both populations: regions without orders and orders without a region. +sidemantic query --metric orders.revenue --metric customers.customer_count --dimension customers.region +``` + +Releases through 0.13.1 anchored a single-model metric query on its first +dimension's model instead: it listed dimension members without metric rows and +dropped metric rows without a matching dimension row. + Composite relationship: ```yaml diff --git a/docs/semantic-input.md b/docs/semantic-input.md index ecddd50dd..284cbcb2b 100644 --- a/docs/semantic-input.md +++ b/docs/semantic-input.md @@ -128,10 +128,20 @@ Derived and ratio metrics reconstruct their source-local aggregate dependencies; metric predicates become HAVING over those reconstructed states. Empty count populations return zero, while nullable sums and averages remain null. +The model that owns the selected metrics anchors an ordinary query in both +engines: dimension models are LEFT JOINed onto it, metric rows without a matching +dimension row form a NULL group, and dimension members without metric rows are +not groups. An Explore's base model replaces that anchor; see +[Which rows a joined query keeps](native-format.md#which-rows-a-joined-query-keeps). + One-hop many-to-one dimension queries can route through a rollup carrying every -join key, including composite keys. The remote dimension model remains the query -domain, so members with no facts retain zero counts. Explicit anchors requiring a -different domain, explicit join kinds, colliding output aliases, uncovered join keys, multi-hop or fanout joins and row filters on +join key, including composite keys. The rollup stands in for the metric model and +is the preserved side, so stored groups whose join key is NULL or unmatched stay +in a NULL dimension group, exactly as in raw planning. Dimension expressions of a +joined model apply only to rows that have a matching dimension row: an expression +such as `COALESCE(name, 'unknown')` leaves unmatched metric rows in the NULL group +on both routes and in both engines. An explicit anchor on +another model, explicit join kinds, colliding output aliases, uncovered join keys, multi-hop or fanout joins and row filters on this join route use ordinary source planning. Compatible stored dimensions and time grains retain their existing routing checks: bucketed timestamps cannot serve finer grains or untruncated timestamps, and week buckets cannot serve months. diff --git a/scripts/benchmark_semantic_sql_planner.py b/scripts/benchmark_semantic_sql_planner.py index fa4151bca..5bdb37f72 100644 --- a/scripts/benchmark_semantic_sql_planner.py +++ b/scripts/benchmark_semantic_sql_planner.py @@ -803,8 +803,8 @@ def _cases(layer: SemanticLayer) -> list[BenchmarkCase]: expected_plan="join_key_preaggregation", expected_rules=("join_key_preaggregation_route_selection",), expected_sql_contains=( - "FROM customers AS customers", - "LEFT JOIN orders_preagg_by_customer AS orders_rollup", + "FROM orders_preagg_by_customer AS orders_rollup", + "FROM customers AS customers) AS customers", ), forbidden_sql_contains="FROM orders\n", min_speedup=1.2, diff --git a/sidemantic-rs/src/sql/generator.rs b/sidemantic-rs/src/sql/generator.rs index 20d3589df..ef8dd9475 100644 --- a/sidemantic-rs/src/sql/generator.rs +++ b/sidemantic-rs/src/sql/generator.rs @@ -437,8 +437,8 @@ impl<'a> SqlGenerator<'a> { } } - // Ordinary queries preserve the dimension domain, including zero-count - // related rows. Aggregate children instead retain their source domain. + // The measure owner is the preserved side, as in each aggregate child: + // dimension models are LEFT JOINed onto it. let base_model = query .consumption_base_model .as_deref() @@ -679,6 +679,8 @@ impl<'a> SqlGenerator<'a> { &available, )); }; + let sql_expr = + self.matched_dimension_sql(sql_expr, dim_ref, &base_model, &join_paths)?; let output_alias = self.output_alias(&dim_ref.model, &dim_ref.alias, &alias_collisions); group_expressions.push(sql_expr.clone()); @@ -1759,15 +1761,14 @@ impl<'a> SqlGenerator<'a> { dimensions: &[DimensionRef], metrics: &[MetricRef], ) -> Option { - // A role describes rows of its owner when that owner supplies the measures. - // Otherwise preserve dimension-first domain selection. + // The model that owns every selected measure is the preserved side: + // dimension models are LEFT JOINed onto it, so facts without a matching + // dimension row land in a NULL group and a breakdown adds up to the + // ungrouped total. Without a single owner, dimensions come first. if let Some(metric) = metrics.first() { if metrics .iter() .all(|candidate| candidate.model == metric.model) - && dimensions.iter().any(|dimension| { - self.graph.role_root_owner(&dimension.model) == Some(metric.model.as_str()) - }) { return Some(metric.model.clone()); } @@ -4591,7 +4592,9 @@ impl<'a> SqlGenerator<'a> { return Ok(None); } let remote_name = remote_names.iter().next().expect("one remote model"); - if explicit_anchor.is_some_and(|anchor| anchor != remote_name) { + // The rollup stands in for the measure model, which this route keeps + // as the preserved side. Any other explicit anchor needs raw planning. + if explicit_anchor.is_some_and(|anchor| anchor != model_name) { return Ok(None); } let Some(remote) = self.graph.get_model(remote_name) else { @@ -4663,6 +4666,11 @@ impl<'a> SqlGenerator<'a> { let rollup_alias = "sidemantic_join_rollup"; let remote_alias = "sidemantic_join_dimension"; let mut select_parts = Vec::new(); + // Remote keys and dimensions are computed inside the joined subquery. + // Evaluated after the LEFT JOIN, an expression such as + // COALESCE(name, 'unknown') would turn the NULL group of unmatched keys + // into an ordinary dimension value. + let mut remote_projections = Vec::new(); for dimension in dimension_refs { let owner = if &dimension.model == model_name { model @@ -4710,6 +4718,11 @@ impl<'a> SqlGenerator<'a> { if let Some(grain) = effective_grain { expression = self.date_trunc_sql(grain, &expression)?; } + if &dimension.model != model_name { + let projected = format!("__sidemantic_dimension_{}", remote_projections.len()); + remote_projections.push(format!("{expression} AS {projected}")); + expression = format!("{remote_alias}.{projected}"); + } select_parts.push(format!( "{expression} AS {}", self.quote_identifier(&dimension.alias) @@ -4735,23 +4748,25 @@ impl<'a> SqlGenerator<'a> { )); } let mut conditions = Vec::new(); - for (from, to) in hop.from_keys.iter().zip(&hop.to_keys) { + for (index, (from, to)) in hop.from_keys.iter().zip(&hop.to_keys).enumerate() { let target = crate::core::key_expression(remote, to, Some(remote_alias), self.dialect)?; + let projected = format!("__sidemantic_join_key_{index}"); + remote_projections.push(format!("{} AS {projected}", self.emit_expression(&target)?)); conditions.push(format!( - "{rollup_alias}.{} = ({})", - self.quote_identifier(from), - self.emit_expression(&target)? + "{rollup_alias}.{} = {remote_alias}.{projected}", + self.quote_identifier(from) )); } - // Match Python's dimension domain: retain remote members without facts. + // Same population as raw planning: every stored fact group is kept and + // an unmatched join key lands in a NULL dimension group. let source = self.preaggregation_source( model, preagg, query.preagg_database.as_deref(), query.preagg_schema.as_deref(), )?; - let mut sql = format!("SELECT\n {}\nFROM {} AS {remote_alias}\nLEFT JOIN {source} AS {rollup_alias}\n ON {}\nGROUP BY {}", - select_parts.join(",\n "), self.model_from_clause(remote, None), conditions.join(" AND "), + let mut sql = format!("SELECT\n {}\nFROM {source} AS {rollup_alias}\nLEFT JOIN (\n SELECT\n {}\n FROM {} AS {remote_alias}\n) AS {remote_alias}\n ON {}\nGROUP BY {}", + select_parts.join(",\n "), remote_projections.join(",\n "), self.model_from_clause(remote, None), conditions.join(" AND "), (1..=dimension_refs.len()).map(|index| index.to_string()).collect::>().join(", ")); if !query.order_by.is_empty() { let mut order_parts = Vec::new(); @@ -4785,11 +4800,18 @@ impl<'a> SqlGenerator<'a> { let Some(output) = output else { return Ok(None); }; - order_parts.push( - format!("{} {direction}", self.quote_identifier(output)) - .trim() - .to_owned(), - ); + // Unmatched join keys add a NULL dimension group; order it as + // raw planning does: first ascending, last descending. MySQL + // and SQL Server have no NULLS FIRST/LAST syntax, and sort + // NULLs exactly that way by default. + let mut ordered = format!("{} {direction}", self.quote_identifier(output)) + .trim() + .to_owned(); + if !matches!(self.dialect, DialectType::MySQL | DialectType::TSQL) { + let nulls = if direction == "DESC" { "LAST" } else { "FIRST" }; + ordered.push_str(&format!(" NULLS {nulls}")); + } + order_parts.push(ordered); } sql.push_str(&format!("\nORDER BY {}", order_parts.join(", "))); } @@ -6076,6 +6098,71 @@ impl<'a> SqlGenerator<'a> { expr.replace("{model}", &self.quote_identifier(alias)) } + /// Keep a joined model's computed dimension NULL on rows its join did not match. + /// + /// Dimension expressions are evaluated after the join. Unguarded, an + /// expression such as COALESCE(name, 'unknown') would give a measure row + /// without a matching dimension row an ordinary value instead of the NULL + /// group, unlike Python, which computes dimensions inside the model CTE. + fn matched_dimension_sql( + &self, + sql_expr: String, + dim_ref: &DimensionRef, + base_model: &str, + join_paths: &HashMap, + ) -> Result { + if dim_ref.model == base_model { + return Ok(sql_expr); + } + let Some(model) = self.graph.get_model(&dim_ref.model) else { + return Ok(sql_expr); + }; + let Some(dimension) = model.get_dimension(&dim_ref.name) else { + return Ok(sql_expr); + }; + // A physical column is already NULL on unmatched rows, also behind a + // time grain; window dimensions are computed in the model CTE. + let Some(authored) = dimension + .sql + .as_deref() + .filter(|_| dimension.window.is_none()) + else { + return Ok(sql_expr); + }; + if matches!( + parse_semantic_expression(authored), + Ok(Expression::Column(_)) + ) { + return Ok(sql_expr); + } + let Some(step) = join_paths.get(&dim_ref.model).and_then(|path| { + path.steps + .iter() + .rev() + .find(|step| step.to_model == dim_ref.model) + }) else { + return Ok(sql_expr); + }; + if step.relationship_type == RelationshipType::Cross || step.to_keys.is_empty() { + return Ok(sql_expr); + } + // An equality join never matches a NULL key, so a non-NULL key on the + // joined side identifies a matched row. + let alias = self.model_alias(&dim_ref.model); + let matched = step + .to_keys + .iter() + .map(|key| { + Ok(format!( + "{} IS NOT NULL", + self.key_sql(model, key, Some(&alias))? + )) + }) + .collect::>>()? + .join(" AND "); + Ok(format!("CASE WHEN {matched} THEN {sql_expr} END")) + } + fn dimension_select_expression( &self, dimension: &crate::core::Dimension, @@ -7386,18 +7473,86 @@ mod tests { .with_metrics(vec!["orders.revenue".into()]) .with_dimensions(vec!["customers.name".into()]) .with_use_preaggregations(true); - assert!(generator - .generate(&query) - .unwrap() - .contains("orders_preagg_daily")); + // The rollup stands in for orders, the preserved side of this query. + for source in [None, Some("orders")] { + let sql = generator.generate_from_model(&query, source).unwrap(); + assert!( + sql.contains("FROM orders_preagg_daily AS sidemantic_join_rollup"), + "{sql}" + ); + assert!(sql.contains("LEFT JOIN (\n SELECT"), "{sql}"); + assert!( + sql.contains("FROM customers AS sidemantic_join_dimension"), + "{sql}" + ); + } + // Any other anchor needs every row of that model, so it reads raw data. let sql = generator - .generate_from_model(&query, Some("orders")) + .generate_from_model(&query, Some("customers")) .unwrap(); assert!(!sql.contains("orders_preagg_daily"), "{sql}"); let local_first = query.with_dimensions(vec!["orders.status".into(), "customers.name".into()]); let sql = generator.generate(&local_first).unwrap(); - assert!(!sql.contains("orders_preagg_daily"), "{sql}"); + assert!(sql.contains("orders_preagg_daily"), "{sql}"); + } + + #[test] + fn joined_computed_dimension_stays_null_for_unmatched_rows() { + let orders: Model = serde_json::from_value(serde_json::json!({ + "name":"orders", "table":"orders", "primary_key":"id", + "dimensions":[{"name":"customer_id"}], + "metrics":[{"name":"revenue","agg":"sum","sql":"amount"}], + "relationships":[{"name":"customers","type":"many_to_one","foreign_key":"customer_id"}], + "pre_aggregations":[{"name":"daily","dimensions":["customer_id"],"measures":["revenue"]}] + })) + .unwrap(); + let customers = Model::new("customers", "id") + .with_table("customers") + .with_dimension(Dimension::categorical("region")) + .with_dimension(Dimension::categorical("name").with_sql("COALESCE(name, 'unknown')")); + let mut graph = SemanticGraph::new(); + graph.add_model(orders).unwrap(); + graph.add_model(customers).unwrap(); + let query = SemanticQuery::new() + .with_metrics(vec!["orders.revenue".into()]) + .with_dimensions(vec!["customers.name".into(), "customers.region".into()]) + .with_order_by(vec!["customers.name".into(), "orders.revenue DESC".into()]); + + // Raw planning evaluates dimensions after the join, so the computed one + // is guarded by the joined key; a physical column needs no guard. + let raw = SqlGenerator::new(&graph).generate(&query).unwrap(); + assert!( + raw.contains("CASE WHEN customers_cte.id IS NOT NULL THEN COALESCE("), + "{raw}" + ); + assert!(raw.contains("customers_cte.region AS region"), "{raw}"); + + // The rollup route computes it inside the joined subquery instead. + let routed = query.clone().with_use_preaggregations(true); + let sql = SqlGenerator::new(&graph).generate(&routed).unwrap(); + let (outer, joined) = sql.split_once("LEFT JOIN (").unwrap(); + assert!(outer.contains("orders_preagg_daily"), "{sql}"); + assert!(!outer.contains("COALESCE(\"sidemantic"), "{sql}"); + assert!( + joined.contains("'unknown') AS __sidemantic_dimension_0"), + "{sql}" + ); + assert!( + sql.contains("ORDER BY name NULLS FIRST, revenue DESC NULLS LAST"), + "{sql}" + ); + + // MySQL and SQL Server have no NULLS FIRST/LAST; their default order + // already places NULLs first ascending and last descending. + for dialect in [DialectType::MySQL, DialectType::TSQL] { + let sql = SqlGenerator::new(&graph) + .with_dialect(dialect) + .generate(&routed) + .unwrap(); + assert!(sql.contains("orders_preagg_daily"), "{sql}"); + assert!(!sql.contains("NULLS"), "{sql}"); + } } #[test] @@ -8370,8 +8525,8 @@ models: let sql = generator.generate(&query).unwrap(); - assert!(sql.contains("LEFT JOIN orders_cte AS orders_cte")); - assert!(sql.contains("customers_cte.id = orders_cte.customers_id")); + assert!(sql.contains("LEFT JOIN customers_cte AS customers_cte")); + assert!(sql.contains("orders_cte.customers_id = customers_cte.id")); } #[test] @@ -8428,8 +8583,8 @@ models: let sql = generator.generate(&query).unwrap(); - assert!(sql.contains("order_items_cte.order_id = shipments_cte.order_id")); - assert!(sql.contains("order_items_cte.item_id = shipments_cte.item_id")); + assert!(sql.contains("shipments_cte.order_id = order_items_cte.order_id")); + assert!(sql.contains("shipments_cte.item_id = order_items_cte.item_id")); assert!(sql.contains(" AND ")); } @@ -8488,10 +8643,14 @@ models: let sql = generator.generate(&query).unwrap(); - assert!(sql.contains("products_cte.tenant_id = order_items_cte.tenant_id")); - assert!(sql.contains("products_cte.product_id = order_items_cte.product_id")); - assert!(sql.contains("order_items_cte.tenant_id = orders_cte.tenant_id")); - assert!(sql.contains("order_items_cte.order_id = orders_cte.order_id")); + for condition in [ + "orders_cte.tenant_id = order_items_cte.tenant_id", + "orders_cte.order_id = order_items_cte.order_id", + "order_items_cte.tenant_id = products_cte.tenant_id", + "order_items_cte.product_id = products_cte.product_id", + ] { + assert!(sql.contains(condition), "{condition}: {sql}"); + } } #[test] diff --git a/sidemantic-rs/src/sql/generator/aggregate_plan.rs b/sidemantic-rs/src/sql/generator/aggregate_plan.rs index 5a417bf22..4cbaf5459 100644 --- a/sidemantic-rs/src/sql/generator/aggregate_plan.rs +++ b/sidemantic-rs/src/sql/generator/aggregate_plan.rs @@ -1530,7 +1530,7 @@ mod tests { } #[test] - fn complete_count_without_inputs_retains_owner_join_and_dimension_domain() { + fn complete_count_without_inputs_retains_owner_join_and_population() { let mut graph = graph(); let mut orders = graph.get_model("orders").unwrap().clone(); let mut count = Metric::derived("opaque_count", "COUNT(*)"); @@ -1542,8 +1542,11 @@ mod tests { .with_dimensions(vec!["customers.region".into()]); let sql = SqlGenerator::new(&graph).generate(&query).unwrap(); assert!(sql.contains("COUNT(*) AS __sidemantic_metric_0"), "{sql}"); - assert!(sql.contains("FROM customers_cte AS customers_cte"), "{sql}"); - assert!(sql.contains("LEFT JOIN orders_cte AS orders_cte"), "{sql}"); + assert!(sql.contains("FROM orders_cte AS orders_cte"), "{sql}"); + assert!( + sql.contains("LEFT JOIN customers_cte AS customers_cte"), + "{sql}" + ); assert_valid_sql(&sql); } diff --git a/sidemantic-rs/src/sql/generator/fanout_complete.rs b/sidemantic-rs/src/sql/generator/fanout_complete.rs index f0ad7ddab..c80b6b6a2 100644 --- a/sidemantic-rs/src/sql/generator/fanout_complete.rs +++ b/sidemantic-rs/src/sql/generator/fanout_complete.rs @@ -237,8 +237,9 @@ pub(super) fn generate_entity_aggregates( rows.with_totals = false; rows.use_preaggregations = false; // Independent children retain their own population before their grouped - // outputs are joined. A single complete expression retains the ordinary - // dimension-domain contract, including COUNT(*) on null-extended rows. + // outputs are joined. A single complete expression follows the ordinary + // anchor: its owner, or an explicit base whose null-extended rows COUNT(*) + // still counts. let source = if independent_source { Some(owner.to_string()) } else { diff --git a/sidemantic-rs/src/sql/generator/imported_totals.rs b/sidemantic-rs/src/sql/generator/imported_totals.rs index af7850834..b3b393537 100644 --- a/sidemantic-rs/src/sql/generator/imported_totals.rs +++ b/sidemantic-rs/src/sql/generator/imported_totals.rs @@ -202,7 +202,7 @@ mod tests { ); // Both aggregates read the same CTEs and join edge. The region filter // may be pushed into the shared customers CTE, so it need not repeat. - assert_eq!(sql.matches("JOIN orders_cte").count(), 2, "{sql}"); + assert_eq!(sql.matches("JOIN customers_cte").count(), 2, "{sql}"); assert!(sql.contains("'EU'"), "{sql}"); polyglot_sql::parse_one(&sql, DialectType::DuckDB).unwrap(); } diff --git a/sidemantic/sql/generator.py b/sidemantic/sql/generator.py index a30fcfe0f..62ee766ca 100644 --- a/sidemantic/sql/generator.py +++ b/sidemantic/sql/generator.py @@ -2108,21 +2108,15 @@ def collect_models_from_metric(metric_ref: str): for model_name in self._extract_models_from_sql(metric.sql): add_model(model_name) - # Role dimensions describe rows of their declaring model, not the full - # population of the reused lookup table. Anchor at that model when it - # also owns the selected measures; an explicit explore base still wins. - aggregate_models = self._find_aggregate_metric_models(metrics) - if len(aggregate_models) == 1: - metric_model = next(iter(aggregate_models)) - for dim in dimensions: - owner = self.graph._role_owners.get(dim.split(".")[0]) - while owner in self.graph._role_owners: - owner = self.graph._role_owners[owner] - if owner == metric_model: - add_model(metric_model) - break - - # Collect from dimensions first (since they define the grain) + # The model that owns the selected measures is the preserved side of the + # join graph: dimension models are LEFT JOINed onto it, so facts without + # a matching dimension row land in a NULL group and a breakdown adds up + # to the ungrouped total. An explicit explore base still wins. + measure_model = self._single_measure_model(metrics) + if measure_model: + add_model(measure_model) + + # Without a single measure owner, dimensions come first in query order. for dim in dimensions: # Remove granularity suffix if present if "__" in dim: @@ -2150,8 +2144,8 @@ def collect_models_from_metric(metric_ref: str): logging.debug("Failed to parse filter for model extraction: %s", filter_expr, exc_info=True) # Directed native relationships restrict which population may anchor a - # query. Keep dimension-first ordering for ordinary graphs, but choose - # a reachable anchor when that ordering would traverse a forbidden edge. + # query. Keep the ordering above for ordinary graphs, but choose a + # reachable anchor when that ordering would traverse a forbidden edge. if ( not self.base_model and len(models) > 1 @@ -2180,6 +2174,22 @@ def collect_models_from_metric(metric_ref: str): return models + def _single_measure_model(self, metric_refs: list[str]) -> str | None: + """The one model whose rows every selected measure aggregates, if there is one.""" + aggregate_models = self._find_aggregate_metric_models(metric_refs) + if aggregate_models: + return next(iter(aggregate_models)) if len(aggregate_models) == 1 else None + # An unowned graph aggregate such as SUM(orders.amount) names its source in SQL. + referenced: set[str] = set() + for metric_ref in metric_refs: + try: + model_name, metric = self.graph.resolve_metric_reference(metric_ref) + except KeyError: + continue + if model_name is None and metric.agg and metric.sql: + referenced.update(self._extract_models_from_sql(metric.sql)) + return next(iter(referenced)) if len(referenced) == 1 else None + def _find_aggregate_metric_models(self, metric_refs: list[str]) -> set[str]: """Find models whose entity keys can de-duplicate selected aggregate leaves.""" models: set[str] = set() @@ -7974,6 +7984,10 @@ def _join_key_preaggregation_route( return None, "no_remote_dimensions" metric_model_name = metric_models[0] + # The rollup stands in for the measure model, which this route keeps as + # the preserved side. Any other explicit anchor needs raw planning. + if self.base_model and self.base_model != metric_model_name: + return None, "explicit_anchor_not_supported" metric_model = self.graph.get_model(metric_model_name) if not metric_model.pre_aggregations: return None, "model_has_no_preaggregations" @@ -8011,6 +8025,10 @@ def _join_key_preaggregation_route( return None, "remote_dimension_not_many_to_one" if self._explicit_join_type_for_path(path[0]) is not None: return None, "explicit_join_type_not_supported" + # The route joins on the stored key columns only; a custom predicate + # decides matches from columns the rollup does not carry. + if path[0].custom_condition: + return None, "custom_join_condition_not_supported" if remote_model_name and remote_model_name != dim_model_name: return None, "multiple_remote_models_not_supported" @@ -8082,6 +8100,11 @@ def _generate_join_key_preaggregation( select_exprs: list[str] = [] output_names: dict[str, str] = {} + # Remote dimensions are computed inside the joined subquery, as raw + # planning computes them in the model CTE. Evaluated after the LEFT + # JOIN, an expression such as COALESCE(name, 'unknown') would turn the + # NULL group of unmatched keys into an ordinary dimension value. + remote_projections: list[str] = [] def register_output_name(output_name: str, *refs: str) -> None: for ref in refs: @@ -8108,13 +8131,18 @@ def dimension_output_name(dim_ref: str, dim_name: str, granularity: str | None) column_expr = f"{rollup_alias}.{self._quote_identifier(column_name)}" if not granularity: column_expr = self._as_grain_type(preagg.granularity, column_expr) + if granularity: + column_expr = self._date_trunc(granularity, column_expr) else: dimension = remote_model.get_dimension(dim_name) dimension_sql = dimension.sql if dimension and dimension.sql else dim_name - column_expr = self._qualify_model_expression(dimension_sql, remote_model_name, remote_alias) + remote_expr = self._qualify_model_expression(dimension_sql, remote_model_name, remote_alias) + if granularity: + remote_expr = self._date_trunc(granularity, remote_expr) + projected_name = self._quote_identifier(f"__sidemantic_dimension_{len(remote_projections)}") + remote_projections.append(f"{remote_expr} AS {projected_name}") + column_expr = f"{self._quote_identifier(remote_alias)}.{projected_name}" - if granularity: - column_expr = self._date_trunc(granularity, column_expr) select_exprs.append(f"{column_expr} AS {self._quote_alias(output_name)}") for metric_ref in metrics: @@ -8147,8 +8175,18 @@ def dimension_output_name(dim_ref: str, dim_name: str, granularity: str | None) direction = f" {parts[1].upper()}" field_name = field_ref.split(".", 1)[1] if "." in field_ref else field_ref output_name = output_names.get(field_ref) or output_names.get(field_name) or field_ref - order_clauses.append(f"{self._quote_alias(output_name)}{direction}") - order_by_clause = "\nORDER BY " + ", ".join(order_clauses) + # Unmatched join keys add a NULL dimension group; order it as + # raw planning does instead of by the database default. The + # target dialect renders or emulates the NULL placement. + descending = direction == " DESC" + order_clauses.append( + exp.Ordered( + this=exp.column(output_name, quoted=True), + desc=descending, + nulls_first=not descending, + ) + ) + order_by_clause = "\n" + exp.Order(expressions=order_clauses).sql(dialect=self.dialect) limit_clause = "" if limit is not None: @@ -8158,10 +8196,22 @@ def dimension_output_name(dim_ref: str, dim_name: str, granularity: str | None) select_exprs_str = ",\n ".join(select_exprs) remote_source = self._model_source_as(remote_model, remote_alias) + quoted_remote_alias = self._quote_identifier(remote_alias) + remote_keys = [ + f"{quoted_remote_alias}.{self._quote_identifier(column)} AS {self._quote_identifier(column)}" + for column in dict.fromkeys(hop.to_columns) + ] + remote_columns = ",\n ".join([*remote_keys, *remote_projections]) + # Same population as raw planning: every stored fact group is kept and + # an unmatched join key lands in a NULL dimension group. return f"""SELECT {select_exprs_str} -FROM {remote_source} -LEFT JOIN {preagg_table} AS {rollup_alias} +FROM {preagg_table} AS {rollup_alias} +LEFT JOIN ( + SELECT + {remote_columns} + FROM {remote_source} +) AS {quoted_remote_alias} ON {" AND ".join(join_conditions)}{group_by_clause}{order_by_clause}{limit_clause}""" def _qualify_model_expression(self, expression_sql: str, model_name: str, alias: str) -> str: diff --git a/tests/adapters/bsl/test_parsing.py b/tests/adapters/bsl/test_parsing.py index 53435d596..b31019d2b 100644 --- a/tests/adapters/bsl/test_parsing.py +++ b/tests/adapters/bsl/test_parsing.py @@ -1279,8 +1279,8 @@ def test_join_aliases_self_join_and_how_roundtrip(self): ) assert "origin_airport_cte" in sql assert "destination_airport_cte" in sql - assert "INNER JOIN flights_cte" in sql - assert "origin_airport_cte.code = flights_cte.origin" in sql + assert "INNER JOIN origin_airport_cte" in sql + assert "flights_cte.origin = origin_airport_cte.code" in sql assert "flights_cte.destination = destination_airport_cte.code" in sql adapter.export(graph, export_path) @@ -1468,7 +1468,7 @@ def test_cross_join_compiles(self): dimensions=["calendar.day"], skip_default_time_dimensions=True, ) - assert "CROSS JOIN facts_cte" in sql + assert "CROSS JOIN calendar_cte" in sql assert "id AS id" in sql conn = duckdb.connect(":memory:") diff --git a/tests/adapters/malloy/test_role_aliases.py b/tests/adapters/malloy/test_role_aliases.py index 6dcf2726d..a14a1b8f4 100644 --- a/tests/adapters/malloy/test_role_aliases.py +++ b/tests/adapters/malloy/test_role_aliases.py @@ -125,10 +125,12 @@ def test_native_custom_join_sql_exports_exactly_and_executes_after_reparse(tmp_p layer.adapter.execute("insert into orders values (10, 1, 20), (11, 2, 30)") for model in reparsed.models.values(): layer.add_model(model) + # The join condition rejects the inactive customer, so that order keeps its + # revenue in a NULL name group and the customer without a match has no group. assert sorted( layer.query(metrics=["orders.revenue"], dimensions=["customers.name"]).fetchall(), - key=lambda row: row[0], - ) == [("Ada", 20), ("Grace", None)] + key=lambda row: row[1], + ) == [("Ada", 20), (None, 30)] @pytest.mark.parametrize( diff --git a/tests/adapters/omni/test_parsing.py b/tests/adapters/omni/test_parsing.py index 925f74868..67de67765 100644 --- a/tests/adapters/omni/test_parsing.py +++ b/tests/adapters/omni/test_parsing.py @@ -312,8 +312,9 @@ def test_omni_one_to_many_join_sql_not_reversed(tmp_path): # Normalize whitespace so we can match the join condition regardless of layout. flat = " ".join(sql.split()) - # Correct join pairs customers.id with orders.customer_id. - assert "customers_cte.id = orders_cte.customer_id" in flat + # Correct join pairs customers.id with orders.customer_id; orders owns the + # measure, so it is the left side of the join. + assert "orders_cte.customer_id = customers_cte.id" in flat # The reversed (buggy) pairing joins the customers FK to the orders PK, and # even references a customer_id column that customers does not have. assert "customers_cte.customer_id = orders_cte.id" not in flat diff --git a/tests/core/test_directed_relationships.py b/tests/core/test_directed_relationships.py index 5f3928805..9acb3e872 100644 --- a/tests/core/test_directed_relationships.py +++ b/tests/core/test_directed_relationships.py @@ -210,7 +210,9 @@ def test_directed_cycle_deduplicates_the_actual_join_target(filter_only): "many_to_one", "many_to_one", ] - generator = SQLGenerator(graph, base_model="orders" if filter_only else None) + # Anchor at orders explicitly. The measure owner would otherwise anchor the + # query and reach orders through the permitted customers -> accounts route. + generator = SQLGenerator(graph, base_model="orders") sql = generator.generate( metrics=["customers.credit", "customers.count", "customers.double_credit"], dimensions=[] if filter_only else ["orders.region"], diff --git a/tests/core/test_directory_loaders.py b/tests/core/test_directory_loaders.py index 97d9026b2..633582bef 100644 --- a/tests/core/test_directory_loaders.py +++ b/tests/core/test_directory_loaders.py @@ -146,7 +146,7 @@ def test_load_from_directory_finalizes_bsl_join_aliases_across_files(tmp_path): sql = layer.compile(metrics=["flights.count"], dimensions=["origin_airport.name"]) assert "origin_airport_cte" in sql - assert "origin_airport_cte.code = flights_cte.origin" in sql + assert "flights_cte.origin = origin_airport_cte.code" in sql def test_load_from_directory_scopes_reused_bsl_join_aliases(tmp_path): diff --git a/tests/joins/test_fact_anchored_joins.py b/tests/joins/test_fact_anchored_joins.py new file mode 100644 index 000000000..2da825819 --- /dev/null +++ b/tests/joins/test_fact_anchored_joins.py @@ -0,0 +1,247 @@ +"""The model that owns the selected measures is the preserved side of a join. + +Dimension models are LEFT JOINed onto it, so a fact whose key is NULL or matches +no dimension row lands in a NULL group and every breakdown adds up to the +ungrouped total. Expected rows come from hand-written SQL on the same data. +""" + +import pytest + +from sidemantic import Dimension, Explore, Metric, Model, Relationship, Segment + + +@pytest.fixture +def shop(layer): + """Customers, orders, order items and tickets with NULL and unmatched keys. + + Order 7 has no customer, order 8 names a customer that does not exist, item + 10 names an order that does not exist and customer 4 has no orders. + """ + layer.conn.execute(""" + create table customers as select * from (values + (1, 'EU'), (2, 'US'), (3, 'US'), (4, 'APAC')) t(id, region); + create table orders as select * from (values + (1, 1, 'completed', 100), (2, 1, 'completed', 50), (3, 2, 'completed', 200), + (4, 2, 'cancelled', 80), (5, 3, 'pending', 40), (6, 3, 'completed', 60), + (7, null, 'completed', 10), (8, 99, 'completed', 5)) t(id, customer_id, status, amount); + create table order_items as select * from (values + (1, 1, 60), (2, 1, 40), (3, 2, 50), (4, 3, 200), (5, 4, 80), (6, 5, 40), + (7, 6, 60), (8, 7, 10), (9, 8, 5), (10, 77, 1)) t(id, order_id, price); + create table tickets as select * from (values + (1, 1), (2, 1), (3, 1), (4, 2), (5, 4)) t(id, customer_id); + """) + layer.add_model( + Model( + name="customers", + table="customers", + primary_key="id", + dimensions=[Dimension(name="region", type="categorical")], + segments=[Segment(name="us", sql="{model}.region = 'US'")], + metrics=[Metric(name="customer_count", agg="count")], + ) + ) + layer.add_model( + Model( + name="orders", + table="orders", + primary_key="id", + relationships=[Relationship(name="customers", type="many_to_one", foreign_key="customer_id")], + dimensions=[Dimension(name="status", type="categorical")], + metrics=[Metric(name="revenue", agg="sum", sql="amount"), Metric(name="order_count", agg="count")], + ) + ) + layer.add_model( + Model( + name="order_items", + table="order_items", + primary_key="id", + relationships=[Relationship(name="orders", type="many_to_one", foreign_key="order_id")], + metrics=[Metric(name="gmv", agg="sum", sql="price"), Metric(name="item_count", agg="count")], + ) + ) + layer.add_model( + Model( + name="tickets", + table="tickets", + primary_key="id", + relationships=[Relationship(name="customers", type="many_to_one", foreign_key="customer_id")], + metrics=[Metric(name="ticket_count", agg="count")], + ) + ) + return layer + + +def _rows(result): + return sorted(result.fetchall(), key=repr) + + +def _hand_sql(layer, sql): + return sorted(layer.conn.execute(sql).fetchall(), key=repr) + + +def test_breakdown_by_joined_dimension_adds_up_to_total(shop): + rows = _rows(shop.query(metrics=["orders.revenue", "orders.order_count"], dimensions=["customers.region"])) + + assert rows == _hand_sql( + shop, + """ + select customers.region, sum(orders.amount), count(orders.id) + from orders left join customers on orders.customer_id = customers.id + group by 1 + """, + ) + # The NULL group holds the order without a customer and the unmatched one. + assert rows == [("EU", 150, 2), ("US", 380, 4), (None, 15, 2)] + total = shop.query(metrics=["orders.revenue", "orders.order_count"]).fetchall() + assert total == [(545, 8)] + assert (sum(row[1] for row in rows), sum(row[2] for row in rows)) == total[0] + + +def test_multi_hop_breakdown_adds_up_to_total(shop): + """order_items -> orders -> customers keeps every item, whichever hop finds no match.""" + rows = _rows(shop.query(metrics=["order_items.gmv", "order_items.item_count"], dimensions=["customers.region"])) + + assert rows == _hand_sql( + shop, + """ + select customers.region, sum(order_items.price), count(order_items.id) + from order_items + left join orders on order_items.order_id = orders.id + left join customers on orders.customer_id = customers.id + group by 1 + """, + ) + assert rows == [("EU", 150, 3), ("US", 380, 4), (None, 16, 3)] + assert shop.query(metrics=["order_items.gmv", "order_items.item_count"]).fetchall() == [(546, 10)] + + +def test_dimensions_from_two_models_keep_every_fact(shop): + rows = _rows(shop.query(metrics=["order_items.gmv"], dimensions=["orders.status", "customers.region"])) + + assert rows == _hand_sql( + shop, + """ + select orders.status, customers.region, sum(order_items.price) + from order_items + left join orders on order_items.order_id = orders.id + left join customers on orders.customer_id = customers.id + group by 1, 2 + """, + ) + assert sum(row[2] for row in rows) == 546 + assert (None, None, 1) in rows + + +@pytest.mark.parametrize("with_second_fact", [False, True]) +def test_cell_does_not_depend_on_other_selected_measures(shop, with_second_fact): + """Adding a measure from another model must not change the revenue of any region.""" + metrics = ["orders.revenue"] + if with_second_fact: + metrics.append("tickets.ticket_count") + rows = shop.query(metrics=metrics, dimensions=["customers.region"]).fetchall() + + revenue = {row[0]: row[1] for row in rows if row[1] is not None} + assert revenue == {"EU": 150, "US": 380, None: 15} + + +def test_graph_level_measure_keeps_the_rows_of_the_model_it_aggregates(shop): + """A graph metric has no owning model; the model named in its SQL is the preserved side.""" + shop.add_metric(Metric(name="graph_revenue", agg="sum", sql="orders.amount")) + shop.add_metric(Metric(name="doubled_revenue", type="derived", sql="orders.revenue * 2")) + + rows = _rows(shop.query(metrics=["graph_revenue", "doubled_revenue"], dimensions=["customers.region"])) + + assert rows == [("EU", 150, 300), ("US", 380, 760), (None, 15, 30)] + + +def test_computed_dimension_stays_null_for_unmatched_facts(shop): + """COALESCE applies to customers that exist; an order without a customer row has no such value.""" + shop.conn.execute("insert into customers values (5, null); insert into orders values (9, 5, 'completed', 7)") + shop.graph.models["customers"].dimensions.append( + Dimension(name="market", type="categorical", sql="COALESCE(region, 'none')") + ) + + rows = _rows(shop.query(metrics=["orders.revenue"], dimensions=["customers.market"])) + + assert rows == _hand_sql( + shop, + """ + select customers.market, sum(orders.amount) + from orders + left join (select id, coalesce(region, 'none') as market from customers) as customers + on orders.customer_id = customers.id + group by 1 + """, + ) + assert rows == [("EU", 150), ("US", 380), ("none", 7), (None, 15)] + + +def test_measure_on_one_side_keeps_its_rows_and_is_not_fanned_out(shop): + """Customers anchor their own count; the customer without orders has a NULL status.""" + rows = _rows(shop.query(metrics=["customers.customer_count"], dimensions=["orders.status"])) + + assert rows == _hand_sql( + shop, + """ + select orders.status, count(distinct customers.id) + from customers left join orders on orders.customer_id = customers.id + group by 1 + """, + ) + assert rows == [("cancelled", 1), ("completed", 3), ("pending", 1), (None, 1)] + + +@pytest.mark.parametrize( + "restriction", + [{"filters": ["customers.region = 'US'"]}, {"segments": ["customers.us"]}], + ids=["filter", "segment"], +) +def test_restriction_on_dimension_model_removes_unmatched_facts(shop, restriction): + """A predicate on a dimension column cannot hold for a fact without that dimension row.""" + assert shop.query(metrics=["orders.revenue"], dimensions=["customers.region"], **restriction).fetchall() == [ + ("US", 380) + ] + assert shop.query(metrics=["orders.revenue"], **restriction).fetchall() == [(380,)] + + +def test_sql_query_keeps_unmatched_facts(shop): + rows = _rows(shop.sql("select customers.region, orders.revenue from orders")) + + assert rows == [("EU", 150), ("US", 380), (None, 15)] + + +def test_explore_on_dimension_model_lists_members_without_facts(shop): + """An Explore names the anchor explicitly: every customer region, matched or not.""" + shop.graph.add_explore(Explore(name="by_customer", model="customers")) + rows = _rows( + shop.query(explore="by_customer", metrics=["orders.revenue", "orders.order_count"], dimensions=["region"]) + ) + + assert rows == _hand_sql( + shop, + """ + select customers.region, sum(orders.amount), count(orders.id) + from customers left join orders on orders.customer_id = customers.id + group by 1 + """, + ) + assert rows == [("APAC", None, 0), ("EU", 150, 2), ("US", 380, 4)] + + +def test_measure_from_dimension_model_keeps_both_populations(shop): + """Selecting a customers measure as well keeps regions without orders and orders without a region.""" + rows = _rows(shop.query(metrics=["orders.revenue", "customers.customer_count"], dimensions=["customers.region"])) + + assert rows == [("APAC", None, 1), ("EU", 150, 1), ("US", 380, 2), (None, 15, 0)] + + +def test_dimension_only_query_starts_from_first_dimension(shop): + """Without a measure there is no fact to preserve; the first dimension's model anchors.""" + assert _rows(shop.query(dimensions=["customers.region", "orders.status"])) == [ + ("APAC", None), + ("EU", "completed"), + ("US", "cancelled"), + ("US", "completed"), + ("US", "pending"), + ] + assert ("completed", None) in shop.query(dimensions=["orders.status", "customers.region"]).fetchall() diff --git a/tests/native-fixtures/composite_keys/expected/result.json b/tests/native-fixtures/composite_keys/expected/result.json index ddef60f29..f79ee9824 100644 --- a/tests/native-fixtures/composite_keys/expected/result.json +++ b/tests/native-fixtures/composite_keys/expected/result.json @@ -6,9 +6,5 @@ { "item_id": 101, "shipment_count": 1 - }, - { - "item_id": 102, - "shipment_count": 0 } ] diff --git a/tests/queries/test_basic.py b/tests/queries/test_basic.py index 9b03ecaad..b62968267 100644 --- a/tests/queries/test_basic.py +++ b/tests/queries/test_basic.py @@ -575,7 +575,8 @@ def test_custom_join_sql_projects_extra_predicate_columns(): rows = df_rows( layer.query(metrics=["orders.revenue"], dimensions=["customers.country"], order_by=["customers.country"]) ) - assert rows == [("Expired", None), ("US", 50)] + # The expired customer row matches no order, so it is not a group of an orders measure. + assert rows == [("US", 50)] def test_compiles_and_executes_columns_with_spaces(): diff --git a/tests/queries/test_semantic_sql_planner.py b/tests/queries/test_semantic_sql_planner.py index 8022f7098..80506f338 100644 --- a/tests/queries/test_semantic_sql_planner.py +++ b/tests/queries/test_semantic_sql_planner.py @@ -2438,8 +2438,10 @@ def test_fanout_join_key_preaggregation_rolls_orders_to_customer_region(semantic assert candidates["join_key_preaggregation"].details["preaggregation_dimensions"] == ["customer_id"] assert candidates["join_key_preaggregation"].details["join_keys"][0]["relationship"] == "many_to_one" assert "orders_preagg_by_customer" in explanation.rewritten_sql - assert "FROM customers AS customers" in explanation.rewritten_sql - assert "LEFT JOIN orders_preagg_by_customer AS orders_rollup" in explanation.rewritten_sql + assert "FROM orders_preagg_by_customer AS orders_rollup" in explanation.rewritten_sql + # The dimension side is a subquery that computes its columns before the join. + assert "LEFT JOIN (SELECT customers.id AS id" in explanation.rewritten_sql + assert "FROM customers AS customers) AS customers" in explanation.rewritten_sql assert "FROM orders\n" not in explanation.rewritten_sql @@ -2535,21 +2537,24 @@ def test_join_key_preaggregation_joins_remote_sql_source(semantic_layer): FROM orders GROUP BY customer_id """) + # Orders of non-premium customers match no row of the filtered source and + # form a NULL region group. Its placement is stated explicitly because the + # engines' SQL rewriters order NULLs differently by default. sql = """ SELECT orders.revenue, customers.region FROM orders - ORDER BY customers.region + ORDER BY customers.region NULLS FIRST """ baseline_sql = _compiled_semantic_sql(semantic_layer, sql, use_preaggregations=False) explanation = _assert_query_matches_baseline(semantic_layer, sql, baseline_sql, ordered=True) assert explanation.chosen_plan == "join_key_preaggregation" - assert "FROM (SELECT id, region, tier FROM customers WHERE tier = 'premium') AS customers" in ( + assert "FROM (SELECT id, region, tier FROM customers WHERE tier = 'premium') AS customers) AS customers" in ( explanation.rewritten_sql ) assert "LEFT JOIN customers AS customers" not in explanation.rewritten_sql - assert "LEFT JOIN orders_preagg_by_customer AS orders_rollup" in explanation.rewritten_sql + assert "FROM orders_preagg_by_customer AS orders_rollup" in explanation.rewritten_sql def test_fanout_join_key_preaggregation_rejects_missing_join_key_rollup(semantic_layer): diff --git a/tests/semantic_conformance/test_aggregate_breadth_parity.py b/tests/semantic_conformance/test_aggregate_breadth_parity.py index 667dec1d3..f8da4734b 100644 --- a/tests/semantic_conformance/test_aggregate_breadth_parity.py +++ b/tests/semantic_conformance/test_aggregate_breadth_parity.py @@ -2,7 +2,7 @@ import pytest -from sidemantic import Dimension, Metric, Model, Relationship, SemanticLayer +from sidemantic import Dimension, Explore, Metric, Model, Relationship, SemanticLayer @pytest.fixture(params=["python", "rust"]) @@ -82,14 +82,17 @@ def test_complete_sql_and_wrappers_run_after_entity_dedup(layer): def test_complete_aggregates_keep_groups_without_source_entities(layer): layer.adapter.execute("insert into raw_items values (5, 99, 'orphan'), (6, 99, 'orphan')") - cursor = layer.query( - metrics=["orders.opaque_count", "orders.average"], - dimensions=["items.category"], - order_by=["items.category"], - ) + query = {"metrics": ["orders.opaque_count", "orders.average"], "order_by": ["items.category"]} + # Orders own the measures, so a category without any order is not a group. + cursor = layer.query(**query, dimensions=["items.category"]) + assert [field[0] for field in cursor.description] == ["category", "opaque_count", "average"] + assert cursor.fetchall() == [("all", 3, 30.0)] + # Anchored at the dimension model, the group is kept. Authored COUNT(*) + # counts the deduplicated null-extended SQL row. Ordinary semantic counts + # instead count source entities and return zero here. + layer.graph.add_explore(Explore(name="by_item", model="items")) + cursor = layer.query(**query, explore="by_item", dimensions=["category"]) assert [field[0] for field in cursor.description] == ["category", "opaque_count", "average"] - # Authored COUNT(*) counts the deduplicated null-extended SQL row. Ordinary - # semantic counts instead count source entities and return zero here. assert cursor.fetchall() == [("all", 3, 30.0), ("orphan", 1, None)] diff --git a/tests/semantic_conformance/test_complete_filters.py b/tests/semantic_conformance/test_complete_filters.py index 1eb4101e6..ccbe710d2 100644 --- a/tests/semantic_conformance/test_complete_filters.py +++ b/tests/semantic_conformance/test_complete_filters.py @@ -4,7 +4,7 @@ import pytest -from sidemantic import Dimension, Metric, Model, Relationship, SecurityPolicy, SemanticLayer +from sidemantic import Dimension, Explore, Metric, Model, Relationship, SecurityPolicy, SemanticLayer from sidemantic.semantic_handoff import UnsupportedSemanticFeaturesError, graph_to_semantic_input @@ -426,7 +426,6 @@ def test_filtered_float_averages_deduplicate_keys_within_each_group( ("a", pytest.approx(5 / 24), 0.125, 0.625, 0.25, 4), ("b", 0.375, None, 0.375, None, 2), ("null-only", None, None, None, None, 1), - ("orphan", None, None, None, None, 0), ] if having == "average": query["filters"].append(f"orders.{average} > 0.3") @@ -542,6 +541,20 @@ def test_complete_row_count_keyed_fanout_and_missing_source_rows(row_count_layer "order_by": ["items.category"], }, ["category", "paid_rows", "ordinary_rows"], + [("a", 3, 3), ("b", 0, 0)], + ) + # Anchored at the dimension model, a category without source rows is a zero group. + layer.graph.add_explore(Explore(name="by_item", model="items")) + assert_result( + layer, + { + "explore": "by_item", + "metrics": ["orders.paid_rows", "orders.ordinary_rows"], + "dimensions": ["category"], + "filters": ["category IS NOT NULL"], + "order_by": ["category"], + }, + ["category", "paid_rows", "ordinary_rows"], [("a", 3, 3), ("b", 0, 0), ("orphan", 0, 0)], ) diff --git a/tests/semantic_conformance/test_filtered_count_family.py b/tests/semantic_conformance/test_filtered_count_family.py index cd1d3984b..63b59d4f4 100644 --- a/tests/semantic_conformance/test_filtered_count_family.py +++ b/tests/semantic_conformance/test_filtered_count_family.py @@ -5,7 +5,7 @@ import pytest -from sidemantic import Dimension, Metric, Model, Relationship, SecurityPolicy, SemanticLayer +from sidemantic import Dimension, Explore, Metric, Model, Relationship, SecurityPolicy, SemanticLayer from sidemantic.core.semantic_layer import SecurityError from sidemantic.semantic_handoff import graph_to_semantic_input @@ -151,16 +151,28 @@ def test_count_family_keyed_fanout_and_orphan_group(counts, restricted): insert into count_family_items values (1,1,'x'),(2,1,'x'),(3,2,'x'),(4,2,'y'), (5,3,'y'),(6,4,'y'),(7,5,'x'),(8,6,'x'),(9,99,'orphan'); """) - # Source restrictions exclude ids4/5 and the orphan group. Without those - # restrictions, the retained orphan still cannot invent a qualifying row. + # Source restrictions exclude ids4/5. Orders own the counts, so the orphan + # category is not one of their groups either way. expected = ( [("x", 3, 3, 0, 3, 3, 0), ("y", 1, 1, 0, 1, 1, 0)] if restricted - else [("orphan", 0, 0, 0, 0, 0, 0), ("x", 4, 4, 0, 4, 4, 0), ("y", 2, 2, 0, 2, 2, 0)] + else [("x", 4, 4, 0, 4, 4, 0), ("y", 2, 2, 0, 2, 2, 0)] ) assert result( counts, dimensions=["items.category"], filters=["items.category IS NOT NULL"], order_by=["items.category"] ) == (["category", *counts[1]], expected) + if not restricted: + # Anchored at the dimension model, the orphan category is retained and + # still cannot invent a qualifying row. + layer.graph.add_explore(Explore(name="by_item", model="items")) + assert result( + counts, + explore="by_item", + metrics=list(counts[1].values()), + dimensions=["category"], + filters=["category IS NOT NULL"], + order_by=["category"], + ) == (["category", *counts[1]], [("orphan", 0, 0, 0, 0, 0, 0), *expected]) @pytest.mark.parametrize("restricted", [False, True]) diff --git a/tests/semantic_conformance/test_many_role_results.py b/tests/semantic_conformance/test_many_role_results.py index 2bd937565..b94b9ced2 100644 --- a/tests/semantic_conformance/test_many_role_results.py +++ b/tests/semantic_conformance/test_many_role_results.py @@ -174,7 +174,8 @@ def test_bridge_join_retains_bridge_keys_when_custom_sql_is_present(rust): def test_target_measures_retain_target_key_grain(rust): model = source() model["models"][1]["metrics"] = [{"name": "sum_ids", "agg": "sum", "sql": "id"}] - assert execute(rust, model, ["orders.id"], metrics=["primary_tags.sum_ids"]) == Counter({(1, 6), (2, 5), (3, None)}) + # Order 3 has no primary tag, so the tag measure has no group for it. + assert execute(rust, model, ["orders.id"], metrics=["primary_tags.sum_ids"]) == Counter({(1, 6), (2, 5)}) def test_composite_junction_keys_do_not_cross_tenants(rust): diff --git a/tests/semantic_conformance/test_rollup_reconstruction.py b/tests/semantic_conformance/test_rollup_reconstruction.py index f27666844..fc14c820d 100644 --- a/tests/semantic_conformance/test_rollup_reconstruction.py +++ b/tests/semantic_conformance/test_rollup_reconstruction.py @@ -4,7 +4,16 @@ import pytest -from sidemantic import Dimension, Metric, Model, PreAggregation, Relationship, SecurityPolicy, SemanticLayer +from sidemantic import ( + Dimension, + Explore, + Metric, + Model, + PreAggregation, + Relationship, + SecurityPolicy, + SemanticLayer, +) from sidemantic.semantic_handoff import graph_to_semantic_input @@ -155,7 +164,7 @@ def add_customers(layer): ) -def test_join_key_rollup_preserves_remote_domain_and_metric_states(layer): +def test_join_key_rollup_preserves_fact_population_and_metric_states(layer): add_customers(layer) build(layer) assert execute( @@ -171,12 +180,95 @@ def test_join_key_rollup_preserves_remote_domain_and_metric_states(layer): ("a", 30, 15.0, 27, 2, 15.0), ("b", 130, 65.0, 112, 3, pytest.approx(130 / 3)), ("c", 50, 50.0, 45, 1, 50.0), - ("empty", None, None, None, 0, None), ], ) -def test_join_key_rollup_with_empty_source_retains_remote_members(layer): +def test_join_key_rollup_keeps_unmatched_and_null_keys_in_null_group(layer): + add_customers(layer) + layer.adapter.execute(""" + insert into rollup_orders values + (7,99,'paid',7,0,'2026-02-02 01:00:00',1),(8,null,'paid',8,0,'2026-02-02 02:00:00',1) + """) + build(layer) + query = {"metrics": ["orders.revenue", "orders.rows"], "dimensions": ["customers.name"]} + order_by = {"order_by": ["customers.name"]} + expected = (["name", "revenue", "rows"], [(None, 15, 2), ("a", 30, 2), ("b", 130, 3), ("c", 50, 1)]) + assert execute(layer, query | order_by) == expected + raw = layer.adapter.execute(layer.compile(**query, **order_by, use_preaggregations=False)) + assert ([column[0] for column in raw.description], raw.fetchall()) == expected + # The breakdown adds up to the ungrouped total on both routes. + assert execute(layer, {"metrics": ["orders.revenue", "orders.rows"]}) == (["revenue", "rows"], [(225, 8)]) + + +@pytest.mark.parametrize( + ("dimension", "expected"), + [ + ("customers.label", [(None, 15, 2), ("a", 30, 2), ("b", 130, 3), ("unknown", 50, 1)]), + ( + "customers.joined__month", + [(None, 15, 2), ("1970-01-01", 50, 1), ("2026-01-01", 30, 2), ("2026-03-01", 130, 3)], + ), + ], + ids=["coalesce", "coalesce-with-grain"], +) +def test_join_key_rollup_computes_remote_dimension_before_join(layer, dimension, expected): + """A dimension that maps NULL to a value must not rename the unmatched-key group. + + Customer c has no name and no join date, so it legitimately falls into the + fallback value. Orders with an unmatched or NULL key have no customer row at + all and stay in the NULL group, on the rollup route as in raw planning. + """ + add_customers(layer) + layer.adapter.execute(""" + alter table rollup_customers add column joined date; + update rollup_customers set joined = case id when 1 then date '2026-01-15' when 2 then date '2026-03-02' end; + update rollup_customers set name = null where id = 3; + insert into rollup_orders values + (7,99,'paid',7,0,'2026-02-02 01:00:00',1),(8,null,'paid',8,0,'2026-02-02 02:00:00',1) + """) + layer.graph.models["customers"].dimensions.extend( + [ + Dimension(name="label", type="categorical", sql="COALESCE(name, 'unknown')"), + Dimension(name="joined", type="time", granularity="day", sql="COALESCE(joined, DATE '1970-01-01')"), + ] + ) + build(layer) + query = {"metrics": ["orders.revenue", "orders.rows"], "dimensions": [dimension], "order_by": [dimension]} + + def normalized(rows): + return [(group if group is None else str(group)[:10], revenue, count) for group, revenue, count in rows] + + _columns, routed_rows = execute(layer, query) + raw_rows = layer.adapter.execute(layer.compile(**query, use_preaggregations=False)).fetchall() + assert normalized(routed_rows) == expected + assert normalized(raw_rows) == expected + + +@pytest.mark.parametrize("dialect", ["mysql", "tsql"]) +def test_join_key_rollup_order_by_renders_for_dialects_without_null_ordering(layer, dialect): + """MySQL and SQL Server reject NULLS FIRST/LAST; their default NULL placement already matches.""" + import sqlglot + + add_customers(layer) + query = { + "metrics": ["orders.revenue"], + "dimensions": ["customers.name"], + "order_by": ["customers.name", "orders.revenue DESC"], + "use_preaggregations": True, + } + sql = layer.compile(**query, dialect=dialect) + assert "orders_preagg_daily" in sql + order_by = sql[sql.rindex("ORDER BY") :].split("--")[0] + assert "NULLS" not in order_by, order_by + assert "DESC" in order_by + statement = sql.split("\n--")[0] + assert sqlglot.parse_one(statement, read=dialect).args["order"] is not None + # DuckDB keeps the explicit placement that orders the unmatched-key group first. + assert "NULLS FIRST" in layer.compile(**query, dialect="duckdb") + + +def test_join_key_rollup_with_empty_source_has_no_groups(layer): add_customers(layer) layer.adapter.execute("delete from rollup_orders") build(layer) @@ -187,7 +279,28 @@ def test_join_key_rollup_with_empty_source_retains_remote_members(layer): "dimensions": ["customers.name"], "order_by": ["customers.name"], }, - ) == (["name", "rows", "avg_amount"], [("a", 0, None), ("b", 0, None), ("c", 0, None), ("empty", 0, None)]) + ) == (["name", "rows", "avg_amount"], []) + + +@pytest.mark.parametrize("empty_source", [False, True]) +def test_dimension_anchored_explore_keeps_members_without_facts(layer, empty_source): + """An Explore based on the dimension model is the explicit way to list every member.""" + add_customers(layer) + layer.graph.add_explore(Explore(name="by_customer", model="customers")) + if empty_source: + layer.adapter.execute("delete from rollup_orders") + build(layer) + query = { + "explore": "by_customer", + "metrics": ["orders.rows", "orders.avg_amount"], + "dimensions": ["name"], + "order_by": ["name"], + } + expected = [("a", 2, 15.0), ("b", 3, 65.0), ("c", 1, 50.0), ("empty", 0, None)] + if empty_source: + expected = [(name, 0, None) for name, _rows, _average in expected] + # The rollup stands in for the measure model, so another anchor reads raw rows. + assert execute(layer, query, routed=False) == (["name", "rows", "avg_amount"], expected) def test_join_key_rollup_alias_order_limit_and_local_dimension(layer): @@ -271,6 +384,10 @@ def test_composite_join_rollup_uses_every_key_and_preserves_literals(layer): create table composite_rollup_customers(tenant integer,id integer,name varchar); insert into composite_rollup_customers values (1,1,'a'),(2,1,'unused'),(1,2,'b'),(2,2,'c'),(1,3,'d'),(1,4,null); """) + # Give the customer whose name falls back to the literal an order, so the + # literal still reaches the result. The (2, 1) customer shares only its id + # with tenant 1's orders and must not receive them. + layer.adapter.execute("insert into rollup_orders values (7,4,'paid',70,0,'2026-02-02 01:00:00',1)") build(layer) assert execute( layer, @@ -285,9 +402,8 @@ def test_composite_join_rollup_uses_every_key_and_preserves_literals(layer): ("a", 2, 15.0), ("b", 2, 40.0), ("c", 1, 90.0), - ("customers.name", 0, None), + ("customers.name", 1, 70.0), ("d", 1, 50.0), - ("unused", 0, None), ], ) @@ -300,14 +416,17 @@ def test_missing_stored_join_key_uses_raw_source(layer): layer, {"metrics": ["orders.rows"], "dimensions": ["customers.name"], "order_by": ["customers.name"]}, routed=False, - ) == (["name", "rows"], [("a", 2), ("b", 3), ("c", 1), ("empty", 0)]) + ) == (["name", "rows"], [("a", 2), ("b", 3), ("c", 1)]) -def test_empty_remote_dimension_domain_stays_empty(layer): +def test_empty_remote_dimension_keeps_facts_in_null_group(layer): add_customers(layer) layer.adapter.execute("delete from rollup_customers") build(layer) - assert execute(layer, {"metrics": ["orders.rows"], "dimensions": ["customers.name"]}) == (["name", "rows"], []) + assert execute(layer, {"metrics": ["orders.rows"], "dimensions": ["customers.name"]}) == ( + ["name", "rows"], + [(None, 6)], + ) def test_lambda_daily_states_roll_up_to_months(layer): @@ -462,8 +581,6 @@ def test_colliding_join_dimension_outputs_keep_raw_contract(layer): @pytest.mark.parametrize("anchor", ["local-first", "role-owner"]) def test_join_rollup_preserves_local_and_role_source_population(layer, anchor): - if layer.engine != "rust": - pytest.skip("Native effective-anchor routing regression") add_customers(layer) if anchor == "role-owner": relationship = layer.graph.models["orders"].relationships[0] @@ -474,7 +591,8 @@ def test_join_rollup_preserves_local_and_role_source_population(layer, anchor): dimensions = ["orders.status", "customers.name"] build(layer) query = {"metrics": ["orders.revenue"], "dimensions": dimensions} - columns, rows = execute(layer, query, routed=False) + # The orders rollup is the preserved side whichever dimension comes first. + columns, rows = execute(layer, query) cursor = layer.adapter.execute(layer.compile(**query, use_preaggregations=False)) assert columns == [column[0] for column in cursor.description] assert sorted(rows, key=str) == sorted(cursor.fetchall(), key=str) diff --git a/tests/semantic_conformance/test_sibling_fanout_parity.py b/tests/semantic_conformance/test_sibling_fanout_parity.py index 3b870d4dc..dcd3ad99d 100644 --- a/tests/semantic_conformance/test_sibling_fanout_parity.py +++ b/tests/semantic_conformance/test_sibling_fanout_parity.py @@ -122,17 +122,37 @@ def test_sibling_groups_preserve_each_item_and_null_population(layer, include_pa ] metrics = ["items.items_value", "items.average", "items.values", "items.rows"] if include_parent: + # Each measure source keeps its own population: the fact whose refund + # group has no items still contributes its total. metrics.append("facts.total") expected = [(*row, total) for row, total in zip(expected, [40, 30, 10, 30], strict=True)] + else: + # Items alone are the preserved side; a refund group without items is + # not a group of an item measure. + expected = [row for row in expected if row[0] != "empty"] + assert ( + expected + == layer.adapter.execute(""" + with refund_groups as ( + select distinct fact_id, label from sibling_refunds + ) + select refund_groups.label, sum(items.value), avg(items.value), count(items.value), count(items.id) + from sibling_items as items + left join sibling_facts as facts on items.fact_id = facts.id + left join refund_groups on refund_groups.fact_id = facts.id + group by refund_groups.label + order by refund_groups.label + """).fetchall() + ) assert execute(layer, metrics=metrics, dimensions=["refunds.label"], order_by=["refunds.label"]) == expected -def test_empty_sibling_population_has_no_groups(layer): +def test_empty_sibling_population_keeps_measure_in_null_group(layer): layer.adapter.execute(""" insert into sibling_facts values (1, 1); insert into sibling_items values (101, 1, 3); """) - assert execute(layer, metrics=["items.items_value", "items.rows"], dimensions=["refunds.label"]) == [] + assert execute(layer, metrics=["items.items_value", "items.rows"], dimensions=["refunds.label"]) == [(None, 3, 1)] def test_source_identity_survives_three_edge_fanout_path(layer):