Skip to content
13 changes: 7 additions & 6 deletions docs/compatibility/yardstick.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,10 @@ and temporary measure views, and applies warning policy when prepared statements
execute. Query expansion uses Sidemantic's production rewriter. This test setup
does not enable multi-statement execution on the public query API.

Sidemantic emits `YardstickWarning` when `AT (ALL ...)` drops an outer filter that
Sidemantic emits `YardstickWarning` when `AT (ALL ...)` or `AT (SET ...)` drops an outer filter that
the remaining evaluation context does not preserve. Python callers can treat
that warning as an error using the standard `warnings` module. Repeated queries
observe the current warning policy. The literal `yardstick('SELECT ...')` table
observe the current warning policy. The literal `yardstick('SELECT ...')` or `yardstick($$SELECT ...$$)` table
wrapper uses the same read-only query rewriting and warning behavior.

Optional environment variables:
Expand All @@ -199,11 +199,11 @@ AT modifiers control the evaluation context of a measure, enabling semi-additive
| `AT (WHERE condition)` | Supported (filters the measure's evaluation context independently of the outer WHERE) |
| `AT (SET dim = value)` | Supported (pins a dimension to a constant value) |
| `AT (SET dim = dim - 1)` | Supported (pins a dimension to a computed expression, e.g., prior period) |
| `AT (SET dim = CURRENT dim - 1)` | Supported (`CURRENT` resolves to the outer query's current value of the dimension) |
| `AT (SET dim = CURRENT dim - 1)` | Supported (`CURRENT` reads the effective context before this modifier) |
| `AT (SET dim IN (values))` | Supported (predicate-form SET, filters the dimension to a set of values) |
| `AT (VISIBLE)` | Supported (evaluates the measure considering the outer WHERE clause) |
| `AT (SET ... VISIBLE)` | Supported (compound modifier combining SET with VISIBLE) |
| Chained AT: `AT (...) AT (...)` | Supported (modifiers applied left to right) |
| Compound AT: `AT (VISIBLE SET ...)` | Supported (parts apply left to right; SET keeps independently visible predicates) |
| Chained AT: `AT (...) AT (...)` | Supported (rightmost clause transforms the context first, then each clause to its left) |
| `AT (ALL expression)` with ad-hoc expressions (e.g., `AT (ALL MONTH(order_date))`) | Supported |
| `AT (SET expression = value)` with ad-hoc expressions | Supported |

Expand All @@ -223,6 +223,7 @@ Bare measure names in non-SEMANTIC queries default to evaluating at the full tab
|---------|--------|
| `FROM view_a JOIN view_b ON ...` in SEMANTIC queries | Supported (measures from different views evaluated against their own base tables) |
| AT modifiers on joined measures | Supported |
| One leading Yardstick source joined to a projection-known non-semantic relation | The Python DuckDB rewriter evaluates visible row membership without multiplying measure inputs. The join itself does not remove rows from the measure's input. |

### GROUP BY Variants

Expand All @@ -231,7 +232,7 @@ Bare measure names in non-SEMANTIC queries default to evaluating at the full tab
| Explicit `GROUP BY col1, col2` | Supported |
| Positional `GROUP BY 1, 2` | Supported (ordinals resolved to SELECT dimensions) |
| `GROUP BY` with extra whitespace | Supported |
| `GROUP BY ROLLUP(...)` | Supported |
| `GROUP BY ROLLUP(...)`, `CUBE(...)`, or `GROUPING SETS (...)` | Supported on DuckDB. Measures evaluate at each grouping set’s grain; a subtotal is distinct from a grouped NULL value. |
| Omitted `GROUP BY` (grouping inferred from SELECT dimensions) | Supported |

---
Expand Down
736 changes: 607 additions & 129 deletions sidemantic-rs/src/sql/rewriter/yardstick.rs

Large diffs are not rendered by default.

954 changes: 697 additions & 257 deletions sidemantic/sql/query_rewriter.py

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions tests/fixtures/sql/yardstick/measures.test
Original file line number Diff line number Diff line change
Expand Up @@ -576,8 +576,8 @@ SEMANTIC SELECT
AGGREGATE(revenue) AT (SET year = year - 1) AT (ALL year) as prior_grand
FROM sales_yearly;
----
2022 NULL 375.0
2023 150.0 375.0
2022 NULL NULL
2023 150.0 150.0

# =============================================================================
# Test: Negative and zero values
Expand Down Expand Up @@ -1634,7 +1634,7 @@ GROUP BY ROLLUP(o.prodName)
ORDER BY o.prodName;
----
Happy 2 13 13 17
NULL 3 NULL NULL NULL
NULL 3 16 16 20
Whizz 1 3 3 3

# Measures/CSEs should be valid in HAVING, and respect context semantics.
Expand Down
76 changes: 76 additions & 0 deletions tests/queries/test_yardstick_joined_visibility.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import pytest

from sidemantic import SemanticLayer
from sidemantic.adapters.yardstick import YardstickAdapter
from tests.queries.yardstick_replay_runtime import replay_runtime


@pytest.mark.parametrize("source_columns", ["*", "year, region, amount, s"])
def test_single_yardstick_source_join_does_not_multiply_or_hide_visible_rows(source_columns):
layer = SemanticLayer(connection="duckdb:///:memory:")
try:
runtime = replay_runtime(layer, YardstickAdapter())
# The physical column s also matches the source alias. A bare s in
# DuckDB would bind to the column, not to the whole source row.
runtime.execute(
"CREATE TABLE sales(year INT, region VARCHAR, amount INT, s INT); "
"INSERT INTO sales VALUES (2023,'North',10,1), (2023,'North',10,1), "
"(2023,'South',20,1), (2024,'North',30,1), (2024,NULL,40,1), (2024,'East',5,1)"
)
runtime.execute(
f"CREATE VIEW sales_v AS SELECT {source_columns}, COUNT(*) AS MEASURE tally, "
"SUM(amount) AS MEASURE revenue FROM sales"
)
query = (
"WITH thresholds AS (SELECT 'North' AS region, 8 AS cutoff UNION ALL "
"SELECT 'North', 9) "
"SELECT year, AGGREGATE(tally), AGGREGATE(revenue) FROM sales_v s "
"JOIN (SELECT region, cutoff FROM thresholds) r "
"ON r.region = s.region WHERE {predicate} GROUP BY year ORDER BY year"
)
assert runtime.execute(query.format(predicate="amount > 7")) == [(2023, 3, 40), (2024, 2, 70)]
assert runtime.execute(query.format(predicate="s.amount > r.cutoff")) == [(2023, 2, 20), (2024, 1, 30)]
finally:
layer.adapter.close()


def test_joined_grouping_does_not_assign_a_right_hand_column_to_the_measure_source():
layer = SemanticLayer(connection="duckdb:///:memory:")
try:
runtime = replay_runtime(layer, YardstickAdapter())
runtime.execute(
"CREATE TABLE raw_sales(region VARCHAR, amount INT); "
"INSERT INTO raw_sales VALUES ('North',10), ('North',11), ('South',20); "
"CREATE VIEW raw_sales_v AS SELECT *, COUNT(*) AS MEASURE tally FROM raw_sales"
)
assert runtime.execute(
"SELECT report_year, AGGREGATE(tally) FROM raw_sales_v s "
"JOIN (SELECT 2026 AS report_year, 'North' AS region) r ON r.region = s.region "
"WHERE s.amount > 0 GROUP BY report_year"
) == [(2026, 3)]
finally:
layer.adapter.close()


@pytest.mark.parametrize(
("year", "join", "where", "expected"),
[
("y", "JOIN (VALUES (2024,'N')) allowed(y,r) USING(y,r)", "y=2024", 30),
("s.y", "JOIN (VALUES (2024,'N')) allowed(y,r) ON s.y=allowed.y AND s.r=allowed.r", "s.y=2024", 30),
("y", "JOIN (VALUES ('N',1),('N',1),('S',0)) allowed(r,keep) USING(r)", "y=2024 AND keep=1", 10),
],
)
def test_joined_visible_set_replaces_year_without_filtering_against_join(year, join, where, expected):
layer = SemanticLayer(connection="duckdb:///:memory:")
try:
runtime = replay_runtime(layer, YardstickAdapter())
runtime.execute(
"CREATE TABLE sales(y INT, r VARCHAR, amount INT); "
"INSERT INTO sales VALUES (2023,'N',10), (2023,'S',20), (2024,'N',40), (2024,'S',80); "
"CREATE VIEW sales_v AS SELECT y, r, SUM(amount) AS MEASURE revenue FROM sales"
)
assert runtime.execute(
f"SELECT {year}, AGGREGATE(revenue) AT (VISIBLE SET y=y-1) FROM sales_v s {join} WHERE {where}"
) == [(2024, expected)]
finally:
layer.adapter.close()
143 changes: 140 additions & 3 deletions tests/queries/test_yardstick_measures_replay.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import hashlib
import os
import re
import subprocess
Expand Down Expand Up @@ -800,11 +801,35 @@ def _apply_statement(layer: SemanticLayer, adapter: YardstickAdapter, statement:
)


def _replay_yardstick_sql_test(path: Path) -> None:
# Yardstick #72 added a mixed fixture to the legacy (non-PEG) corpus. Its
# attached-store metadata, session/transaction behavior, and implicit measures
# are native extension integration checks, not Sidemantic query capabilities.
# Require review of any changed fixture so no new assertions disappear silently.
_DEFINITION_STORE_FIXTURE_SHA256 = "8301ba931eee4043223d37efb30e819a2b957a4d1e9e93f92cf984fd33da6e82"
_DEFINITION_STORE_PORTABLE_STATEMENTS = {13, 16, 28, 72}
_DEFINITION_STORE_PORTABLE_QUERIES = {23, 42, 54, 75}


def _portable_definition_store_records(path: Path) -> tuple[list[_StatementBlock], list[_QueryBlock]]:
digest = hashlib.sha256(path.read_text().rstrip("\n").encode()).hexdigest()
assert digest == _DEFINITION_STORE_FIXTURE_SHA256, (
f"{path}: upstream definition-store fixture changed; review the native/portable replay boundary"
)
statements, queries = _parse_measures_test(path)
portable_statements = [record for record in statements if record.line in _DEFINITION_STORE_PORTABLE_STATEMENTS]
portable_queries = [record for record in queries if record.line in _DEFINITION_STORE_PORTABLE_QUERIES]
assert {record.line for record in portable_statements} == _DEFINITION_STORE_PORTABLE_STATEMENTS
assert {record.line for record in portable_queries} == _DEFINITION_STORE_PORTABLE_QUERIES
return portable_statements, portable_queries


def _replay_yardstick_sql_test(
path: Path, records: tuple[list[_StatementBlock], list[_QueryBlock]] | None = None
) -> None:
if not path.exists():
pytest.skip(f"Yardstick SQL test file not found: {path}")

statements, queries = _parse_measures_test(path)
statements, queries = _parse_measures_test(path) if records is None else records
assert queries, f"No query blocks parsed from Yardstick SQL test: {path}"

layer = SemanticLayer(connection="duckdb:///:memory:")
Expand Down Expand Up @@ -856,7 +881,42 @@ def test_yardstick_upstream_create_view_definitions():
@pytest.mark.yardstick_upstream
def test_yardstick_upstream_sql_replay():
for path in _yardstick_upstream_sql_test_paths():
_replay_yardstick_sql_test(path)
if path.name == "definition_store.test":
_replay_yardstick_sql_test(path, _portable_definition_store_records(path))
else:
_replay_yardstick_sql_test(path)


def test_changed_definition_store_fixture_requires_review(tmp_path):
path = tmp_path / "definition_store.test"
path.write_text("query I\nSELECT 123;\n----\n456\n")

with pytest.raises(AssertionError, match="review the native/portable replay boundary"):
_portable_definition_store_records(path)


def test_replay_binds_measure_and_grouping_projection_aliases(tmp_path):
path = tmp_path / "aliases.test"
path.write_text(
"""statement ok
CREATE TABLE sales(region VARCHAR, amount INT);

statement ok
INSERT INTO sales VALUES ('N', 10), ('N', 20), ('S', 50);

statement ok
CREATE VIEW sales_v AS SELECT region, SUM(amount) AS MEASURE revenue,
COUNT(*) AS MEASURE orders FROM sales;

query TIIR rowsort
SELECT LOWER(region) AS area, AGGREGATE(revenue) AS r, AGGREGATE(orders) AS n, r/n AS mean
FROM sales_v GROUP BY area;
----
n\t30\t2\t15.0
s\t50\t1\t50.0
"""
)
_replay_yardstick_sql_test(path)


def test_parse_statement_record_preserves_batch_and_unterminated_error(tmp_path):
Expand Down Expand Up @@ -1107,3 +1167,80 @@ def test_definition_coverage_is_corpus_wide_without_dropping_plain_sql(tmp_path)
_replay_yardstick_sql_test(ordinary)
with pytest.raises(AssertionError, match="eligible upstream corpus"):
_assert_definition_corpus_matches([ordinary])


@pytest.mark.parametrize("keyword", ["ALL", "SET", "WHERE", "VISIBLE"])
def test_at_where_quoted_modifier_word(keyword):
from tests.queries.yardstick_replay_runtime import replay_runtime

layer = SemanticLayer(connection="duckdb:///:memory:")
runtime = replay_runtime(layer, YardstickAdapter())
runtime.execute(
f"CREATE TABLE lexical(k VARCHAR, amount INTEGER); INSERT INTO lexical VALUES ('{keyword}', 1), ('other', 150)"
)
runtime.execute("CREATE VIEW lexical_v AS SELECT k, SUM(amount) AS MEASURE revenue FROM lexical")
assert runtime.execute(f"SELECT AGGREGATE(revenue) AT (WHERE k = '{keyword}') FROM lexical_v") == [(1,)]


@pytest.mark.parametrize("star", ["*", "v.*"])
def test_explicit_yardstick_star_can_exclude_logical_measures(star):
from tests.queries.yardstick_replay_runtime import replay_runtime

layer = SemanticLayer(connection="duckdb:///:memory:")
runtime = replay_runtime(layer, YardstickAdapter())
runtime.execute(
"CREATE TABLE named(year INTEGER, region VARCHAR, amount INTEGER, revenue INTEGER); "
"INSERT INTO named VALUES (2023,'N',1,100), (2024,'S',3,200)"
)
runtime.execute(
"CREATE VIEW named_v AS SELECT year, region, amount, SUM(amount) AS MEASURE revenue, "
"COUNT(*) AS MEASURE tally FROM named"
)
query = (
f"SELECT {star} EXCLUDE(amount, revenue, tally), AGGREGATE(revenue) AT (ALL) "
"FROM named_v v GROUP BY ALL ORDER BY year"
)
assert runtime.execute(query) == [(2023, "N", 4), (2024, "S", 4)]
with pytest.raises(Exception, match="missing_column"):
runtime.execute(query.replace("amount,", "missing_column,"))


@pytest.mark.parametrize("grouping", ["ROLLUP(region)", "CUBE(region)", "GROUPING SETS ((region), ())"])
def test_yardstick_subtotal_preserves_filter_mode_and_real_null(grouping):
from tests.queries.yardstick_replay_runtime import replay_runtime

layer = SemanticLayer(connection="duckdb:///:memory:")
runtime = replay_runtime(layer, YardstickAdapter())
runtime.execute(
"CREATE TABLE subtotal(region VARCHAR, amount INTEGER, included BOOLEAN); "
"INSERT INTO subtotal VALUES (NULL,2,true), (NULL,7,false), ('N',3,true), ('S',5,true)"
)
runtime.execute("CREATE VIEW subtotal_v AS SELECT region, included, SUM(amount) AS MEASURE revenue FROM subtotal")
assert runtime.execute(
"SELECT region, GROUPING(region) AS subtotal_flag, AGGREGATE(revenue), "
"revenue AT (VISIBLE), revenue FROM subtotal_v WHERE included "
f"GROUP BY {grouping} ORDER BY subtotal_flag, region NULLS FIRST"
) == [(None, 0, 2, 2, 9), ("N", 0, 3, 3, 3), ("S", 0, 5, 5, 5), (None, 1, 10, 10, 17)]


def test_yardstick_grouping_set_keeps_other_dimensions_and_ctas():
from tests.queries.yardstick_replay_runtime import replay_runtime

layer = SemanticLayer(connection="duckdb:///:memory:")
runtime = replay_runtime(layer, YardstickAdapter())
runtime.execute(
"CREATE TABLE mixed(year INTEGER, region VARCHAR, amount INTEGER); "
"INSERT INTO mixed VALUES (2023,NULL,2), (2023,'N',3), (2024,'N',5)"
)
runtime.execute(
"CREATE VIEW mixed_v AS SELECT year, region, COUNT(*) AS MEASURE tally FROM mixed; "
"CREATE TABLE subtotals AS SELECT year, region, GROUPING(region) AS subtotal_flag, "
"AGGREGATE(tally) AS n FROM mixed_v GROUP BY year, GROUPING SETS ((region), ())"
)
assert runtime.execute("SELECT * FROM subtotals ORDER BY year, subtotal_flag, region NULLS FIRST") == [
(2023, None, 0, 1),
(2023, "N", 0, 1),
(2023, None, 1, 2),
(2024, "N", 0, 1),
(2024, None, 1, 1),
]
Loading