From cdd3e10c304305c28315c64f4badf3f043d94e46 Mon Sep 17 00:00:00 2001 From: Mike Bridge Date: Thu, 19 Nov 2026 09:43:05 -0600 Subject: [PATCH 1/4] fix(semantic-layer): normalize dates only for resampling Keep DATE objects for raw and non-resampled results so XLSX date-only formatting is unchanged. Convert typed dates for resample-bearing queries to provide the DatetimeIndex required after pivoting. Cover SQL parity, export bytes, null and empty results, filter bounds, and existing time-comparison refusal. --- .../semantic-member-selections.mdx | 12 + superset/semantic_layers/mapper.py | 6 + .../semantic_layers/date_result_test.py | 337 ++++++++++++++++++ .../unit_tests/semantic_layers/mapper_test.py | 64 ++++ 4 files changed, 419 insertions(+) create mode 100644 tests/unit_tests/semantic_layers/date_result_test.py diff --git a/docs/docs/using-superset/semantic-member-selections.mdx b/docs/docs/using-superset/semantic-member-selections.mdx index 02694e4c5b8a..fc559c6cc701 100644 --- a/docs/docs/using-superset/semantic-member-selections.mdx +++ b/docs/docs/using-superset/semantic-member-selections.mdx @@ -91,6 +91,18 @@ charts. The host refuses these queries before reading cached chart results to avoid showing incorrect comparison values. SQL dataset comparisons and semantic queries without time shifts are unaffected. +## Daily resampling of dates + +Semantic views can use a DATE dimension for daily resampling, including filling +gaps between observations. Raw results and exports without resampling keep their +date-only representation. Resampled results use the same datetime representation +as ordinary dataset time-series charts: CSV shows calendar dates for daily +buckets, while XLSX cells include the midnight time component. + +As with ordinary datasets, a NULL time-axis bucket cannot be resampled; filter out +NULL dates before applying resampling. Resampling does not enable time comparison +on semantic views. + ## Clearing dashboard filters **Clear all** stages empty values for in-scope filters; **Apply** commits the diff --git a/superset/semantic_layers/mapper.py b/superset/semantic_layers/mapper.py index a6f43c3a31e1..759d21d83703 100644 --- a/superset/semantic_layers/mapper.py +++ b/superset/semantic_layers/mapper.py @@ -499,6 +499,12 @@ def map_semantic_result_to_query_result( # Core data df=stringify_extension_columns(semantic_result.results).to_pandas( integer_object_nulls=True, + # Resampling needs a DatetimeIndex after pivoting. Keep DATE objects + # otherwise so raw and non-resampled exports retain date-only cells. + date_as_object=not any( + operation.get("operation") == "resample" + for operation in query_object.post_processing + ), ), query=query_str, duration=duration, diff --git a/tests/unit_tests/semantic_layers/date_result_test.py b/tests/unit_tests/semantic_layers/date_result_test.py new file mode 100644 index 000000000000..a2d3a1e36331 --- /dev/null +++ b/tests/unit_tests/semantic_layers/date_result_test.py @@ -0,0 +1,337 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Temporal result conversion must support calculations without changing exports.""" + +from datetime import date, datetime, timedelta, timezone +from io import BytesIO +from typing import cast +from unittest.mock import MagicMock + +import pandas as pd +import pyarrow as pa +import pytest +from openpyxl import load_workbook +from openpyxl.worksheet.worksheet import Worksheet +from pytest_mock import MockerFixture +from superset_core.semantic_layers.types import SemanticResult + +from superset.common.chart_data import ChartDataResultFormat +from superset.common.query_context import QueryContext +from superset.common.query_context_processor import QueryContextProcessor +from superset.connectors.sqla.models import SqlaTable, TableColumn +from superset.exceptions import InvalidPostProcessingError +from superset.models.helpers import QueryResult +from superset.semantic_layers.exceptions import SemanticLayerQueryRejectedError +from superset.semantic_layers.mapper import ( + _ViewMetadata, + get_results, + map_semantic_result_to_query_result, + ValidatedQueryObject, +) +from superset.semantic_layers.models import SemanticView +from superset.utils.core import GenericDataType +from superset.utils.json import json_int_dttm_ser + + +def _date_frame(query: ValidatedQueryObject) -> pd.DataFrame: + """Convert typed provider dates through the real final mapper boundary.""" + table: pa.Table = pa.table( + { + "day": pa.array([date(2026, 1, 5), date(2026, 1, 7)], type=pa.date32()), + "amount": [1, 3], + } + ) + return _mapped_frame(table, query) + + +def _mapped_frame(table: pa.Table, query: ValidatedQueryObject) -> pd.DataFrame: + """Map provider output without discovery or network calls.""" + return map_semantic_result_to_query_result( + SemanticResult(requests=[], results=table), + query, + timedelta(0), + _ViewMetadata(metrics=(), dimensions=()), + ).df + + +def _resample_query() -> ValidatedQueryObject: + """Build the pivot/resample/flatten chain emitted by a daily time-series chart.""" + return ValidatedQueryObject( + metrics=["amount"], + columns=["day"], + post_processing=[ + { + "operation": "pivot", + "options": { + "index": ["day"], + "columns": [], + "aggregates": {"amount": {"operator": "mean"}}, + "drop_missing_columns": True, + }, + }, + { + "operation": "resample", + "options": {"method": "asfreq", "rule": "1D", "fill_value": 0}, + }, + {"operation": "flatten"}, + ], + ) + + +def test_semantic_date_daily_resample_fills_gaps() -> None: + """A date-typed semantic axis supports the chart's real post-processing chain.""" + query: ValidatedQueryObject = _resample_query() + result: pd.DataFrame = query.exec_post_processing(_date_frame(query)) + assert result["amount"].tolist() == [1, 0, 3] + assert result["day"].dt.date.tolist() == [ + date(2026, 1, 5), + date(2026, 1, 6), + date(2026, 1, 7), + ] + + +def test_ordinary_date_axis_normalization_and_exports() -> None: + """Record SQL DATE axis normalization and its existing export presentation.""" + dataset: SqlaTable = SqlaTable( + columns=[TableColumn(column_name="day", type="DATE", is_dttm=True)], + offset=0, + ) + query: ValidatedQueryObject = ValidatedQueryObject( + columns=["day"], metrics=["amount"], granularity="day" + ) + frame: pd.DataFrame = dataset.normalize_df(_date_frame(query), query) + assert pd.api.types.is_datetime64_any_dtype(frame["day"]) + context: MagicMock = MagicMock(result_format=ChartDataResultFormat.CSV) + context.datasource.data = {} + processor: QueryContextProcessor = QueryContextProcessor( + cast(QueryContext, context) + ) + csv_result: object = processor.get_data( + frame.copy(), [GenericDataType.TEMPORAL, GenericDataType.NUMERIC] + ) + assert isinstance(csv_result, bytes) + assert csv_result.decode("utf-8-sig").splitlines()[1] == "2026-01-05,1" + context.result_format = ChartDataResultFormat.XLSX + xlsx_result: object = processor.get_data( + frame.copy(), [GenericDataType.TEMPORAL, GenericDataType.NUMERIC] + ) + assert isinstance(xlsx_result, bytes) + sheet: Worksheet = cast(Worksheet, load_workbook(BytesIO(xlsx_result)).active) + assert sheet["A2"].number_format == "YYYY-MM-DD HH:MM:SS" + + +@pytest.mark.parametrize( + "result_format", + [ChartDataResultFormat.JSON, ChartDataResultFormat.CSV, ChartDataResultFormat.XLSX], +) +def test_semantic_date_raw_results_keep_date_presentation( + result_format: ChartDataResultFormat, +) -> None: + """Raw dates retain their JSON instant, CSV text and spreadsheet date format.""" + query: ValidatedQueryObject = ValidatedQueryObject( + columns=["day"], metrics=["amount"] + ) + context: MagicMock = MagicMock(result_format=result_format) + context.datasource.data = {} + processor: QueryContextProcessor = QueryContextProcessor( + cast(QueryContext, context) + ) + result: object = processor.get_data( + _date_frame(query), [GenericDataType.TEMPORAL, GenericDataType.NUMERIC] + ) + if result_format == ChartDataResultFormat.JSON: + assert isinstance(result, list) + assert json_int_dttm_ser(result[0]["day"]) == json_int_dttm_ser( + date(2026, 1, 5) + ) + elif result_format == ChartDataResultFormat.CSV: + assert isinstance(result, bytes) + assert result.decode("utf-8-sig").splitlines() == [ + "day,amount", + "2026-01-05,1", + "2026-01-07,3", + ] + else: + assert isinstance(result, bytes) + sheet: Worksheet = cast(Worksheet, load_workbook(BytesIO(result)).active) + assert sheet["A2"].value == datetime(2026, 1, 5) + assert sheet["A2"].number_format == "YYYY-MM-DD" + + +@pytest.mark.parametrize("resampling", [False, True]) +@pytest.mark.parametrize( + "result_format", + list(ChartDataResultFormat.table_like()) + [ChartDataResultFormat.JSON], +) +def test_semantic_date_exports_match_unchanged_raw_or_resampled_sql( + resampling: bool, result_format: ChartDataResultFormat +) -> None: + """Raw bytes stay identical; newly supported resampled exports match SQL output.""" + query: ValidatedQueryObject = ( + _resample_query() if resampling else ValidatedQueryObject() + ) + # Build the independent pre-change raw frame rather than use the changed mapper. + expected: pd.DataFrame = pd.DataFrame( + {"day": [date(2026, 1, 5), date(2026, 1, 7)], "amount": [1, 3]} + ) + actual: pd.DataFrame = _date_frame(query) + if resampling: + dataset: SqlaTable = SqlaTable( + columns=[TableColumn(column_name="day", type="DATE", is_dttm=True)], + offset=0, + ) + query.granularity = "day" + expected = query.exec_post_processing(dataset.normalize_df(expected, query)) + actual = query.exec_post_processing(actual) + context: MagicMock = MagicMock(result_format=result_format) + context.datasource.data = {} + processor: QueryContextProcessor = QueryContextProcessor( + cast(QueryContext, context) + ) + coltypes: list[GenericDataType] = [ + GenericDataType.TEMPORAL, + GenericDataType.NUMERIC, + ] + assert processor.get_data(actual, coltypes) == processor.get_data( + expected, coltypes + ) + + +@pytest.mark.parametrize("date_type", [pa.date32(), pa.date64()]) +def test_semantic_date_resample_nulls_follow_sql_behavior( + date_type: pa.DataType, +) -> None: + """Preserve SQL's rejection of a NULL bucket rather than silently drop it.""" + table: pa.Table = pa.table( + { + "day": pa.array([date(2026, 1, 5), None, date(2026, 1, 7)], type=date_type), + "amount": [1, 99, 3], + } + ) + query: ValidatedQueryObject = _resample_query() + frame: pd.DataFrame = _mapped_frame(table, query) + assert pd.isna(frame["day"].iloc[1]) + dataset: SqlaTable = SqlaTable( + columns=[TableColumn(column_name="day", type="DATE", is_dttm=True)], offset=0 + ) + query.granularity = "day" + ordinary: pd.DataFrame = dataset.normalize_df(table.to_pandas(), query) + with pytest.raises(InvalidPostProcessingError, match="requires DatetimeIndex"): + query.exec_post_processing(ordinary) + with pytest.raises(InvalidPostProcessingError, match="requires DatetimeIndex"): + query.exec_post_processing(frame) + + +def test_semantic_date_resample_empty_skips_post_processing( + mocker: MockerFixture, +) -> None: + """The host's empty-result guard keeps typed empty DATE results successful.""" + table: pa.Table = pa.table( + {"day": pa.array([], type=pa.date32()), "amount": pa.array([], type=pa.int64())} + ) + query: ValidatedQueryObject = _resample_query() + result: QueryResult = map_semantic_result_to_query_result( + SemanticResult(requests=[], results=table), + query, + timedelta(0), + _ViewMetadata(metrics=(), dimensions=()), + ) + mocker.patch("superset.semantic_layers.models.get_results", return_value=result) + post_processing: MagicMock = mocker.patch.object(query, "exec_post_processing") + assert SemanticView().get_query_result(query).df.empty + post_processing.assert_not_called() + + +@pytest.mark.parametrize("resampling", [False, True]) +@pytest.mark.parametrize("tz", [None, "UTC"]) +def test_semantic_date_conversion_leaves_timestamps_unchanged( + resampling: bool, tz: str | None +) -> None: + """Native timestamps, including UTC instants, do not change dtype or values.""" + table: pa.Table = pa.table( + { + "day": pa.array( + [datetime(2026, 1, 5, tzinfo=timezone.utc if tz else None)], + type=pa.timestamp("us", tz=tz), + ), + "amount": [1], + } + ) + query: ValidatedQueryObject = ( + _resample_query() if resampling else ValidatedQueryObject() + ) + pd.testing.assert_frame_equal( + _mapped_frame(table, query), table.to_pandas(integer_object_nulls=True) + ) + + +@pytest.mark.parametrize("resampling", [False, True]) +def test_semantic_date_conversion_keeps_text_and_exact_nullable_ints( + resampling: bool, +) -> None: + """Do not guess text dates or convert nullable identifiers through float64.""" + table: pa.Table = pa.table( + { + "day": ["2026-01-05", "2026-01-07"], + "amount": [1, 3], + "id": pa.array([2**53 + 1, None], type=pa.int64()), + } + ) + query: ValidatedQueryObject = ( + _resample_query() if resampling else ValidatedQueryObject() + ) + frame: pd.DataFrame = _mapped_frame(table, query) + pd.testing.assert_frame_equal(frame, table.to_pandas(integer_object_nulls=True)) + assert frame["id"].iloc[0] == 2**53 + 1 + if resampling: + with pytest.raises(InvalidPostProcessingError, match="requires DatetimeIndex"): + query.exec_post_processing(frame) + + +@pytest.mark.parametrize( + "operation", ["rolling", "cum", "contribution", "compare", "prophet"] +) +def test_non_resample_operations_do_not_change_date_representation( + operation: str, +) -> None: + """Selecting other post-processing does not opt raw DATE output into timestamps.""" + query: ValidatedQueryObject = ValidatedQueryObject( + post_processing=[{"operation": operation}] + ) + assert type(_date_frame(query)["day"].iloc[0]) is date + + +def test_resample_does_not_bypass_semantic_time_comparison_refusal( + mocker: MockerFixture, +) -> None: + """A real semantic datasource still rejects unsupported offsets before dispatch.""" + query: ValidatedQueryObject = ValidatedQueryObject( + datasource=SemanticView(id=7, name="Orders"), + metrics=["amount"], + columns=["day"], + time_offsets=["1 week ago"], + post_processing=[*_resample_query().post_processing], + ) + dispatch: MagicMock = mocker.patch( + "superset.semantic_layers.mapper._dispatch_semantic_query" + ) + with pytest.raises( + SemanticLayerQueryRejectedError, match="Time comparison is not yet supported" + ): + get_results(query) + dispatch.assert_not_called() diff --git a/tests/unit_tests/semantic_layers/mapper_test.py b/tests/unit_tests/semantic_layers/mapper_test.py index 981d632c26ef..fbbf697835b8 100644 --- a/tests/unit_tests/semantic_layers/mapper_test.py +++ b/tests/unit_tests/semantic_layers/mapper_test.py @@ -2164,6 +2164,70 @@ def test_get_results_without_time_offsets( pd.testing.assert_frame_equal(result.df, main_df) +def test_date_resample_preserves_date_range( + mock_datasource: MagicMock, mocker: MockerFixture +) -> None: + """DATE conversion leaves the provider's inclusive/exclusive range unchanged.""" + mock_datasource.implementation._dimensions = { + Dimension("orders.order_date", "order_date", pa.date32()) + } + mock_datasource.implementation.get_table = mocker.Mock( + side_effect=[ + SemanticResult( + requests=[], + results=pa.table( + { + "order_date": pa.array( + [date(2026, 1, 5), date(2026, 1, 7)], type=pa.date32() + ), + "total_sales": [1, 3], + } + ), + ), + ] + ) + query: ValidatedQueryObject = ValidatedQueryObject( + datasource=mock_datasource, + from_dttm=datetime(2026, 1, 5), + to_dttm=datetime(2026, 1, 8), + metrics=["total_sales"], + columns=["order_date"], + granularity="order_date", + post_processing=[ + { + "operation": "pivot", + "options": { + "index": ["order_date"], + "columns": [], + "aggregates": { + "total_sales": {"operator": "mean"}, + }, + }, + }, + { + "operation": "resample", + "options": {"method": "asfreq", "rule": "1D", "fill_value": 0}, + }, + {"operation": "flatten"}, + ], + ) + result: QueryResult = get_results(query) + frame: pd.DataFrame = query.exec_post_processing(result.df) + assert frame["total_sales"].tolist() == [1, 0, 3] + assert frame["order_date"].dt.date.tolist() == [ + date(2026, 1, 5), + date(2026, 1, 6), + date(2026, 1, 7), + ] + main_query: SemanticQuery = mock_datasource.implementation.get_table.call_args_list[ + 0 + ].args[0] + assert {(item.operator, item.value) for item in main_query.filters} == { + (Operator.GREATER_THAN_OR_EQUAL, datetime(2026, 1, 5)), + (Operator.LESS_THAN, datetime(2026, 1, 8)), + } + + def test_get_results_with_single_time_offset( mock_datasource: MagicMock, mocker: MockerFixture, From bb1e4cd971cb389c6a81813df6f73291ec02ee50 Mon Sep 17 00:00:00 2001 From: Mike Bridge Date: Thu, 19 Nov 2026 10:03:11 -0600 Subject: [PATCH 2/4] fix(semantic-layer): preserve date series during resampling Cast only base-axis and granularity DATE columns so resampling does not change DATE series labels or exports. Cover date and timestamp axes against ordinary dataset output, consolidate serializer fixtures, and document the separate forecast limitation. --- .../semantic-member-selections.mdx | 8 +- superset/semantic_layers/mapper.py | 37 +++- .../semantic_layers/date_result_test.py | 166 +++++++----------- .../unit_tests/semantic_layers/mapper_test.py | 4 +- 4 files changed, 99 insertions(+), 116 deletions(-) diff --git a/docs/docs/using-superset/semantic-member-selections.mdx b/docs/docs/using-superset/semantic-member-selections.mdx index fc559c6cc701..45cc8c46fe4f 100644 --- a/docs/docs/using-superset/semantic-member-selections.mdx +++ b/docs/docs/using-superset/semantic-member-selections.mdx @@ -91,17 +91,17 @@ charts. The host refuses these queries before reading cached chart results to avoid showing incorrect comparison values. SQL dataset comparisons and semantic queries without time shifts are unaffected. -## Daily resampling of dates +## Resampling of dates -Semantic views can use a DATE dimension for daily resampling, including filling -gaps between observations. Raw results and exports without resampling keep their +Semantic views can resample a DATE axis, for example to fill daily gaps between +observations. DATE series labels, raw results and exports without resampling keep their date-only representation. Resampled results use the same datetime representation as ordinary dataset time-series charts: CSV shows calendar dates for daily buckets, while XLSX cells include the midnight time component. As with ordinary datasets, a NULL time-axis bucket cannot be resampled; filter out NULL dates before applying resampling. Resampling does not enable time comparison -on semantic views. +on semantic views. Forecasting on a DATE axis is not addressed by this conversion. ## Clearing dashboard filters diff --git a/superset/semantic_layers/mapper.py b/superset/semantic_layers/mapper.py index 759d21d83703..c77c18ad2dbc 100644 --- a/superset/semantic_layers/mapper.py +++ b/superset/semantic_layers/mapper.py @@ -99,6 +99,7 @@ ) from superset.utils.core import ( FilterOperator, + get_base_axis_labels, QueryObjectFilterClause, TIME_COMPARISON, ) @@ -457,6 +458,30 @@ def _coerce_empty_result( ) +def _cast_resample_date_axes(table: pa.Table, query_object: QueryObject) -> pa.Table: + """Give resample's DatetimeIndex guard typed axes without changing DATE series.""" + if not any( + operation.get("operation") == "resample" + for operation in query_object.post_processing + ): + return table + + axis_labels: set[str | None] = { + *get_base_axis_labels(query_object.columns), + query_object.granularity, + } + index: int + field: pa.Field + for index, field in enumerate(table.schema): + if field.name in axis_labels and pa.types.is_date(field.type): + table = table.set_column( + index, + field.with_type(pa.timestamp("ms")), + table.column(index).cast(pa.timestamp("ms")), + ) + return table + + def map_semantic_result_to_query_result( semantic_result: SemanticResult, query_object: ValidatedQueryObject, @@ -497,15 +522,9 @@ def map_semantic_result_to_query_result( return QueryResult( # Core data - df=stringify_extension_columns(semantic_result.results).to_pandas( - integer_object_nulls=True, - # Resampling needs a DatetimeIndex after pivoting. Keep DATE objects - # otherwise so raw and non-resampled exports retain date-only cells. - date_as_object=not any( - operation.get("operation") == "resample" - for operation in query_object.post_processing - ), - ), + df=stringify_extension_columns( + _cast_resample_date_axes(semantic_result.results, query_object) + ).to_pandas(integer_object_nulls=True), query=query_str, duration=duration, # Template filters - not applicable to semantic layers diff --git a/tests/unit_tests/semantic_layers/date_result_test.py b/tests/unit_tests/semantic_layers/date_result_test.py index a2d3a1e36331..dd8af44c88c5 100644 --- a/tests/unit_tests/semantic_layers/date_result_test.py +++ b/tests/unit_tests/semantic_layers/date_result_test.py @@ -36,16 +36,13 @@ from superset.connectors.sqla.models import SqlaTable, TableColumn from superset.exceptions import InvalidPostProcessingError from superset.models.helpers import QueryResult -from superset.semantic_layers.exceptions import SemanticLayerQueryRejectedError from superset.semantic_layers.mapper import ( _ViewMetadata, - get_results, map_semantic_result_to_query_result, ValidatedQueryObject, ) from superset.semantic_layers.models import SemanticView from superset.utils.core import GenericDataType -from superset.utils.json import json_int_dttm_ser def _date_frame(query: ValidatedQueryObject) -> pd.DataFrame: @@ -69,11 +66,26 @@ def _mapped_frame(table: pa.Table, query: ValidatedQueryObject) -> pd.DataFrame: ).df +def _sql_date_dataset() -> SqlaTable: + """Build the ordinary DATE-axis baseline without a database connection.""" + return SqlaTable( + columns=[TableColumn(column_name="day", type="DATE", is_dttm=True)], offset=0 + ) + + +def _processor(result_format: ChartDataResultFormat) -> QueryContextProcessor: + """Use the real export serializer with an offline query context.""" + context: MagicMock = MagicMock(result_format=result_format) + context.datasource.data = {} + return QueryContextProcessor(cast(QueryContext, context)) + + def _resample_query() -> ValidatedQueryObject: """Build the pivot/resample/flatten chain emitted by a daily time-series chart.""" return ValidatedQueryObject( metrics=["amount"], columns=["day"], + granularity="day", post_processing=[ { "operation": "pivot", @@ -105,72 +117,18 @@ def test_semantic_date_daily_resample_fills_gaps() -> None: ] -def test_ordinary_date_axis_normalization_and_exports() -> None: - """Record SQL DATE axis normalization and its existing export presentation.""" - dataset: SqlaTable = SqlaTable( - columns=[TableColumn(column_name="day", type="DATE", is_dttm=True)], - offset=0, - ) - query: ValidatedQueryObject = ValidatedQueryObject( - columns=["day"], metrics=["amount"], granularity="day" - ) - frame: pd.DataFrame = dataset.normalize_df(_date_frame(query), query) - assert pd.api.types.is_datetime64_any_dtype(frame["day"]) - context: MagicMock = MagicMock(result_format=ChartDataResultFormat.CSV) - context.datasource.data = {} - processor: QueryContextProcessor = QueryContextProcessor( - cast(QueryContext, context) - ) - csv_result: object = processor.get_data( - frame.copy(), [GenericDataType.TEMPORAL, GenericDataType.NUMERIC] - ) - assert isinstance(csv_result, bytes) - assert csv_result.decode("utf-8-sig").splitlines()[1] == "2026-01-05,1" - context.result_format = ChartDataResultFormat.XLSX - xlsx_result: object = processor.get_data( - frame.copy(), [GenericDataType.TEMPORAL, GenericDataType.NUMERIC] - ) - assert isinstance(xlsx_result, bytes) - sheet: Worksheet = cast(Worksheet, load_workbook(BytesIO(xlsx_result)).active) - assert sheet["A2"].number_format == "YYYY-MM-DD HH:MM:SS" - - -@pytest.mark.parametrize( - "result_format", - [ChartDataResultFormat.JSON, ChartDataResultFormat.CSV, ChartDataResultFormat.XLSX], -) -def test_semantic_date_raw_results_keep_date_presentation( - result_format: ChartDataResultFormat, -) -> None: - """Raw dates retain their JSON instant, CSV text and spreadsheet date format.""" +def test_semantic_date_raw_xlsx_keeps_date_cell_format() -> None: + """Raw spreadsheet cells retain date-only formatting.""" query: ValidatedQueryObject = ValidatedQueryObject( columns=["day"], metrics=["amount"] ) - context: MagicMock = MagicMock(result_format=result_format) - context.datasource.data = {} - processor: QueryContextProcessor = QueryContextProcessor( - cast(QueryContext, context) - ) - result: object = processor.get_data( + result: object = _processor(ChartDataResultFormat.XLSX).get_data( _date_frame(query), [GenericDataType.TEMPORAL, GenericDataType.NUMERIC] ) - if result_format == ChartDataResultFormat.JSON: - assert isinstance(result, list) - assert json_int_dttm_ser(result[0]["day"]) == json_int_dttm_ser( - date(2026, 1, 5) - ) - elif result_format == ChartDataResultFormat.CSV: - assert isinstance(result, bytes) - assert result.decode("utf-8-sig").splitlines() == [ - "day,amount", - "2026-01-05,1", - "2026-01-07,3", - ] - else: - assert isinstance(result, bytes) - sheet: Worksheet = cast(Worksheet, load_workbook(BytesIO(result)).active) - assert sheet["A2"].value == datetime(2026, 1, 5) - assert sheet["A2"].number_format == "YYYY-MM-DD" + assert isinstance(result, bytes) + sheet: Worksheet = cast(Worksheet, load_workbook(BytesIO(result)).active) + assert sheet["A2"].value == datetime(2026, 1, 5) + assert sheet["A2"].number_format == "YYYY-MM-DD" @pytest.mark.parametrize("resampling", [False, True]) @@ -191,18 +149,11 @@ def test_semantic_date_exports_match_unchanged_raw_or_resampled_sql( ) actual: pd.DataFrame = _date_frame(query) if resampling: - dataset: SqlaTable = SqlaTable( - columns=[TableColumn(column_name="day", type="DATE", is_dttm=True)], - offset=0, + expected = query.exec_post_processing( + _sql_date_dataset().normalize_df(expected, query) ) - query.granularity = "day" - expected = query.exec_post_processing(dataset.normalize_df(expected, query)) actual = query.exec_post_processing(actual) - context: MagicMock = MagicMock(result_format=result_format) - context.datasource.data = {} - processor: QueryContextProcessor = QueryContextProcessor( - cast(QueryContext, context) - ) + processor: QueryContextProcessor = _processor(result_format) coltypes: list[GenericDataType] = [ GenericDataType.TEMPORAL, GenericDataType.NUMERIC, @@ -226,11 +177,7 @@ def test_semantic_date_resample_nulls_follow_sql_behavior( query: ValidatedQueryObject = _resample_query() frame: pd.DataFrame = _mapped_frame(table, query) assert pd.isna(frame["day"].iloc[1]) - dataset: SqlaTable = SqlaTable( - columns=[TableColumn(column_name="day", type="DATE", is_dttm=True)], offset=0 - ) - query.granularity = "day" - ordinary: pd.DataFrame = dataset.normalize_df(table.to_pandas(), query) + ordinary: pd.DataFrame = _sql_date_dataset().normalize_df(table.to_pandas(), query) with pytest.raises(InvalidPostProcessingError, match="requires DatetimeIndex"): query.exec_post_processing(ordinary) with pytest.raises(InvalidPostProcessingError, match="requires DatetimeIndex"): @@ -252,9 +199,7 @@ def test_semantic_date_resample_empty_skips_post_processing( _ViewMetadata(metrics=(), dimensions=()), ) mocker.patch("superset.semantic_layers.models.get_results", return_value=result) - post_processing: MagicMock = mocker.patch.object(query, "exec_post_processing") - assert SemanticView().get_query_result(query).df.empty - post_processing.assert_not_called() + pd.testing.assert_frame_equal(SemanticView().get_query_result(query).df, result.df) @pytest.mark.parametrize("resampling", [False, True]) @@ -303,9 +248,7 @@ def test_semantic_date_conversion_keeps_text_and_exact_nullable_ints( query.exec_post_processing(frame) -@pytest.mark.parametrize( - "operation", ["rolling", "cum", "contribution", "compare", "prophet"] -) +@pytest.mark.parametrize("operation", ["rolling", "cum", "contribution", "compare"]) def test_non_resample_operations_do_not_change_date_representation( operation: str, ) -> None: @@ -316,22 +259,43 @@ def test_non_resample_operations_do_not_change_date_representation( assert type(_date_frame(query)["day"].iloc[0]) is date -def test_resample_does_not_bypass_semantic_time_comparison_refusal( - mocker: MockerFixture, +@pytest.mark.parametrize("axis_type", [pa.date32(), pa.date64(), pa.timestamp("us")]) +@pytest.mark.parametrize("base_axis", [False, True]) +def test_resample_preserves_date_series_labels( + axis_type: pa.DataType, + base_axis: bool, ) -> None: - """A real semantic datasource still rejects unsupported offsets before dispatch.""" - query: ValidatedQueryObject = ValidatedQueryObject( - datasource=SemanticView(id=7, name="Orders"), - metrics=["amount"], - columns=["day"], - time_offsets=["1 week ago"], - post_processing=[*_resample_query().post_processing], + """Normalize only the selected axis, matching SQL's unchanged DATE legends.""" + table: pa.Table = pa.table( + { + "day": pa.array( + [datetime(2026, 1, 5), datetime(2026, 1, 7)], type=axis_type + ), + "cohort": pa.array([date(2025, 11, 1)] * 2, type=pa.date32()), + "amount": [1, 3], + } + ) + query: ValidatedQueryObject = _resample_query() + query.columns = ( + [ + { + "sqlExpression": "day", + "label": "day", + "columnType": "BASE_AXIS", + }, + "cohort", + ] + if base_axis + else ["day", "cohort"] ) - dispatch: MagicMock = mocker.patch( - "superset.semantic_layers.mapper._dispatch_semantic_query" + query.granularity = None if base_axis else "day" + query.post_processing[0]["options"]["columns"] = ["cohort"] + dataset: SqlaTable = _sql_date_dataset() + dataset.columns.append(TableColumn(column_name="cohort", type="DATE", is_dttm=True)) + expected: pd.DataFrame = query.exec_post_processing( + dataset.normalize_df(table.to_pandas(), query) ) - with pytest.raises( - SemanticLayerQueryRejectedError, match="Time comparison is not yet supported" - ): - get_results(query) - dispatch.assert_not_called() + actual: pd.DataFrame = query.exec_post_processing(_mapped_frame(table, query)) + assert actual.columns.tolist() == ["day", "amount, 2025-11-01"] + assert actual.iloc[:, 1].tolist() == [1, 0, 3] + pd.testing.assert_frame_equal(actual, expected, check_dtype=False) diff --git a/tests/unit_tests/semantic_layers/mapper_test.py b/tests/unit_tests/semantic_layers/mapper_test.py index fbbf697835b8..f230e7b4288a 100644 --- a/tests/unit_tests/semantic_layers/mapper_test.py +++ b/tests/unit_tests/semantic_layers/mapper_test.py @@ -2164,10 +2164,10 @@ def test_get_results_without_time_offsets( pd.testing.assert_frame_equal(result.df, main_df) -def test_date_resample_preserves_date_range( +def test_date_resample_fills_gaps_through_get_results( mock_datasource: MagicMock, mocker: MockerFixture ) -> None: - """DATE conversion leaves the provider's inclusive/exclusive range unchanged.""" + """Provider DATE results fill chart gaps without shifting the selected range.""" mock_datasource.implementation._dimensions = { Dimension("orders.order_date", "order_date", pa.date32()) } From 7526cda2997545f6845701e10137310b48bcee68 Mon Sep 17 00:00:00 2001 From: Mike Bridge Date: Thu, 19 Nov 2026 10:20:34 -0600 Subject: [PATCH 3/4] test(semantic-layer): guard non-resample date axes Give raw-export and other-operation queries a temporal axis so the tests catch accidental removal of the resample-only conversion gate. --- tests/unit_tests/semantic_layers/date_result_test.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/unit_tests/semantic_layers/date_result_test.py b/tests/unit_tests/semantic_layers/date_result_test.py index dd8af44c88c5..8bfb67276d3c 100644 --- a/tests/unit_tests/semantic_layers/date_result_test.py +++ b/tests/unit_tests/semantic_layers/date_result_test.py @@ -120,7 +120,7 @@ def test_semantic_date_daily_resample_fills_gaps() -> None: def test_semantic_date_raw_xlsx_keeps_date_cell_format() -> None: """Raw spreadsheet cells retain date-only formatting.""" query: ValidatedQueryObject = ValidatedQueryObject( - columns=["day"], metrics=["amount"] + columns=["day"], metrics=["amount"], granularity="day" ) result: object = _processor(ChartDataResultFormat.XLSX).get_data( _date_frame(query), [GenericDataType.TEMPORAL, GenericDataType.NUMERIC] @@ -141,7 +141,7 @@ def test_semantic_date_exports_match_unchanged_raw_or_resampled_sql( ) -> None: """Raw bytes stay identical; newly supported resampled exports match SQL output.""" query: ValidatedQueryObject = ( - _resample_query() if resampling else ValidatedQueryObject() + _resample_query() if resampling else ValidatedQueryObject(granularity="day") ) # Build the independent pre-change raw frame rather than use the changed mapper. expected: pd.DataFrame = pd.DataFrame( @@ -254,7 +254,7 @@ def test_non_resample_operations_do_not_change_date_representation( ) -> None: """Selecting other post-processing does not opt raw DATE output into timestamps.""" query: ValidatedQueryObject = ValidatedQueryObject( - post_processing=[{"operation": operation}] + granularity="day", post_processing=[{"operation": operation}] ) assert type(_date_frame(query)["day"].iloc[0]) is date From e8fbddc7dea98540dfb2e0905003e6bded6f2097 Mon Sep 17 00:00:00 2001 From: Mike Bridge Date: Fri, 20 Nov 2026 08:34:20 -0600 Subject: [PATCH 4/4] test(semantic-layer): strengthen date resample regression assertions Narrow semantic filters before checking temporal bounds so full-tree mypy can verify the assertions. Snapshot empty results and assert post-processing is skipped so removing the empty guard fails the regression test. Addresses review threads 4639084179 and 4639084190 on #46378. --- tests/unit_tests/semantic_layers/date_result_test.py | 5 ++++- tests/unit_tests/semantic_layers/mapper_test.py | 7 ++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/unit_tests/semantic_layers/date_result_test.py b/tests/unit_tests/semantic_layers/date_result_test.py index 8bfb67276d3c..a8a0e8020042 100644 --- a/tests/unit_tests/semantic_layers/date_result_test.py +++ b/tests/unit_tests/semantic_layers/date_result_test.py @@ -198,8 +198,11 @@ def test_semantic_date_resample_empty_skips_post_processing( timedelta(0), _ViewMetadata(metrics=(), dimensions=()), ) + expected: pd.DataFrame = result.df.copy() mocker.patch("superset.semantic_layers.models.get_results", return_value=result) - pd.testing.assert_frame_equal(SemanticView().get_query_result(query).df, result.df) + post_processing: MagicMock = mocker.spy(query, "exec_post_processing") + pd.testing.assert_frame_equal(SemanticView().get_query_result(query).df, expected) + post_processing.assert_not_called() @pytest.mark.parametrize("resampling", [False, True]) diff --git a/tests/unit_tests/semantic_layers/mapper_test.py b/tests/unit_tests/semantic_layers/mapper_test.py index 9c3a92143384..525dce8a7f3f 100644 --- a/tests/unit_tests/semantic_layers/mapper_test.py +++ b/tests/unit_tests/semantic_layers/mapper_test.py @@ -2222,7 +2222,12 @@ def test_date_resample_fills_gaps_through_get_results( main_query: SemanticQuery = mock_datasource.implementation.get_table.call_args_list[ 0 ].args[0] - assert {(item.operator, item.value) for item in main_query.filters} == { + assert main_query.filters is not None + conditions: list[Filter] = [ + item for item in main_query.filters if isinstance(item, Filter) + ] + assert len(conditions) == len(main_query.filters) + assert {(item.operator, item.value) for item in conditions} == { (Operator.GREATER_THAN_OR_EQUAL, datetime(2026, 1, 5)), (Operator.LESS_THAN, datetime(2026, 1, 8)), }