Skip to content

Commit 483542e

Browse files
fix(chart-data): return 400 for malformed post-processing options (#44953)
1 parent 1705596 commit 483542e

7 files changed

Lines changed: 330 additions & 8 deletions

File tree

‎superset/common/query_object.py‎

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
import inspect
2121
import logging
22+
from collections.abc import Callable
2223
from datetime import datetime
2324
from pprint import pformat
2425
from typing import Any, cast, NamedTuple, TYPE_CHECKING
@@ -27,6 +28,7 @@
2728
from flask_babel import gettext as _
2829
from jinja2.exceptions import TemplateError
2930
from pandas import DataFrame
31+
from pandas.errors import DataError
3032
from superset_core.semantic_layers.view import SemanticView as SemanticViewABC
3133

3234
from superset import feature_flag_manager
@@ -799,7 +801,7 @@ def exec_post_processing(self, df: DataFrame) -> DataFrame:
799801
:param df: DataFrame returned from database model.
800802
:return: new DataFrame to which all post processing operations have been
801803
applied
802-
:raises QueryObjectValidationError: If the post processing operation
804+
:raises InvalidPostProcessingError: If the post processing operation
803805
is incorrect
804806
"""
805807
logger.debug("post_processing: \n %s", pformat(self.post_processing))
@@ -813,7 +815,8 @@ def exec_post_processing(self, df: DataFrame) -> DataFrame:
813815
# ``OPERATIONS`` is the authoritative list of built-in operations;
814816
# excludes escape_separator/unescape_separator (str -> str helpers
815817
# used by flatten, not DataFrame post-processing operations).
816-
if operation in pandas_postprocessing.OPERATIONS:
818+
is_builtin = operation in pandas_postprocessing.OPERATIONS
819+
if is_builtin:
817820
func = getattr(pandas_postprocessing, operation)
818821
else:
819822
extra_ops = pandas_postprocessing.build_extra_ops_map(
@@ -830,9 +833,81 @@ def exec_post_processing(self, df: DataFrame) -> DataFrame:
830833
options = post_process.get("options", {})
831834
if operation == "resample":
832835
options = self._resolve_resample_options(options)
833-
df = func(df, **options)
836+
df = self._exec_operation(func, operation, is_builtin, df, options)
834837
return df
835838

839+
@staticmethod
840+
def _exec_operation(
841+
func: Callable[..., DataFrame],
842+
operation: str,
843+
is_builtin: bool,
844+
df: DataFrame,
845+
options: dict[str, Any],
846+
) -> DataFrame:
847+
"""
848+
Run one post-processing operation, reporting a bad request as one.
849+
850+
An operation is driven entirely by the request's ``options`` dict, which
851+
``ChartDataPostProcessingOperationSchema`` accepts as an untyped
852+
``fields.Dict``. Nothing validates an option before it reaches pandas,
853+
so a malformed one surfaces as whatever pandas raises. Those are
854+
bad-request failures, and left unwrapped they reach
855+
``app.errorhandler(Exception)``, which answers 500.
856+
857+
``ImportError`` is deliberately not among them: a missing optional
858+
dependency, such as scipy for a ``rolling`` ``win_type``, is a
859+
deployment matter rather than a bad request.
860+
861+
:param func: The operation to run.
862+
:param operation: Its name, for the message and to tell the two kinds
863+
of operation apart.
864+
:param is_builtin: Whether ``func`` is a built-in operation rather than
865+
one registered through
866+
``EXTRA_PANDAS_POSTPROCESSING_OPS``.
867+
:param df: DataFrame to run the operation on.
868+
:param options: Options for the operation, straight from the request.
869+
:return: DataFrame with the operation applied
870+
:raises InvalidPostProcessingError: If the options are unusable
871+
"""
872+
try:
873+
return func(df, **options)
874+
except (AttributeError, DataError, KeyError, TypeError, ValueError) as ex:
875+
if not is_builtin:
876+
# The operation came from ``EXTRA_PANDAS_POSTPROCESSING_OPS``,
877+
# which the operator owns and this code cannot reason about. A
878+
# failure inside it is a fault in that operation rather than a
879+
# malformed request, so leave it to the error handler.
880+
raise
881+
# The caller turns this into a message on the response without
882+
# logging it, and these types are broad enough to also cover a
883+
# genuine fault in a built-in operation, so keep the traceback.
884+
logger.warning(
885+
"Post-processing operation %s failed and was reported as a bad request",
886+
operation,
887+
exc_info=True,
888+
)
889+
if isinstance(ex, KeyError):
890+
# Every KeyError a built-in operation raises names a column or
891+
# MultiIndex level the options asked for and the result does
892+
# not have. `str(KeyError)` is only the repr'd key, which alone
893+
# reads as a bare quoted string.
894+
raise InvalidPostProcessingError(
895+
_(
896+
"The `%(operation)s` post-processing operation "
897+
"references a column or level that is not in the query "
898+
"result: %(name)s",
899+
operation=operation,
900+
name=ex.args[0] if ex.args else ex,
901+
)
902+
) from ex
903+
raise InvalidPostProcessingError(
904+
_(
905+
"The `%(operation)s` post-processing operation failed: %(message)s",
906+
operation=operation,
907+
message=str(ex),
908+
)
909+
) from ex
910+
836911
def _resolve_resample_options(self, options: dict[str, Any]) -> dict[str, Any]:
837912
"""
838913
Translate the `fill_time_range` flag into explicit resample boundaries.

‎superset/models/helpers.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3398,8 +3398,6 @@ def get_query_result(self, query_object: QueryObject) -> QueryResult:
33983398
df = query_object.exec_post_processing(df)
33993399
except InvalidPostProcessingError as ex:
34003400
raise QueryObjectValidationError(ex.message) from ex
3401-
except (TypeError, pd.errors.DataError) as ex:
3402-
raise QueryObjectValidationError(str(ex)) from ex
34033401

34043402
# Update result with processed data
34053403
result.df = df

‎superset/semantic_layers/models.py‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
from dataclasses import dataclass, field
2828
from typing import Any, cast, TYPE_CHECKING
2929

30-
import pandas as pd
3130
import pyarrow as pa
3231
import sqlalchemy as sa
3332
from flask_appbuilder import Model
@@ -453,8 +452,6 @@ def get_query_result(self, query_object: QueryObject) -> QueryResult:
453452
result.df = query_object.exec_post_processing(result.df)
454453
except InvalidPostProcessingError as ex:
455454
raise QueryObjectValidationError(ex.message) from ex
456-
except (TypeError, pd.errors.DataError) as ex:
457-
raise QueryObjectValidationError(str(ex)) from ex
458455
return result
459456

460457
def get_query_str(self, query_obj: QueryObjectDict) -> str:

‎superset/translations/messages.pot‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14532,6 +14532,14 @@ msgstr ""
1453214532
msgid "The `%(field)s` field must be a string."
1453314533
msgstr ""
1453414534

14535+
#, python-format
14536+
msgid "The `%(operation)s` post-processing operation failed: %(message)s"
14537+
msgstr ""
14538+
14539+
#, python-format
14540+
msgid "The `%(operation)s` post-processing operation references a column or level that is not in the query result: %(name)s"
14541+
msgstr ""
14542+
1453514543
msgid "The affected charts or dashboards changed. Review the updated impact and type DELETE again to continue."
1453614544
msgstr ""
1453714545

‎tests/unit_tests/models/helpers_test.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7322,3 +7322,58 @@ def compile_not_in() -> str:
73227322
kql = compile_not_in()
73237323
assert "isnull(state)" in kql
73247324
assert "IS NULL" not in kql
7325+
7326+
7327+
def test_get_query_result_leaves_a_custom_operation_fault_unwrapped(
7328+
database: "Database",
7329+
) -> None:
7330+
"""
7331+
A fault inside a custom operation must not be reported as a bad request.
7332+
7333+
An operation registered through ``EXTRA_PANDAS_POSTPROCESSING_OPS`` is the
7334+
operator's own code. ``exec_post_processing`` leaves its exceptions alone,
7335+
and this path must not convert them either, or a bug in that operation
7336+
answers 400 and tells the caller their request was malformed.
7337+
"""
7338+
from datetime import timedelta
7339+
from unittest.mock import patch
7340+
7341+
import pandas as pd
7342+
7343+
from superset.common.query_object import QueryObject
7344+
from superset.connectors.sqla.models import SqlaTable
7345+
from superset.exceptions import QueryObjectValidationError
7346+
from superset.models.helpers import QueryResult
7347+
7348+
def _raise_type_error(df: pd.DataFrame, **options: Any) -> pd.DataFrame:
7349+
raise TypeError("a fault inside the operator's own code")
7350+
7351+
table = SqlaTable(table_name="t", database=database)
7352+
df = pd.DataFrame({"metric": [1.0, 2.0]})
7353+
7354+
query_object = QueryObject(
7355+
row_limit=10,
7356+
post_processing=[{"operation": "_raise_type_error"}],
7357+
)
7358+
7359+
with (
7360+
patch.object(
7361+
table,
7362+
"query",
7363+
return_value=QueryResult(
7364+
df=df,
7365+
query="SELECT 1",
7366+
duration=timedelta(0),
7367+
sql_shifted_temporal_labels=set(),
7368+
),
7369+
),
7370+
patch.object(table, "normalize_df", return_value=df),
7371+
patch.dict(
7372+
"superset.common.query_object.current_app.config",
7373+
{"EXTRA_PANDAS_POSTPROCESSING_OPS": [_raise_type_error]},
7374+
),
7375+
pytest.raises(TypeError, match="operator's own code") as excinfo,
7376+
):
7377+
table.get_query_result(query_object)
7378+
7379+
assert not isinstance(excinfo.value, QueryObjectValidationError)

‎tests/unit_tests/queries/query_object_test.py‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,14 @@
1616
# under the License.
1717
from contextlib import contextmanager
1818
from datetime import datetime
19+
from typing import Any
1920
from unittest.mock import call, patch, PropertyMock
2021

2122
import pandas as pd
2223
import pytest
2324
from flask_appbuilder.security.sqla.models import User
2425
from pandas import DataFrame
26+
from pandas.errors import DataError
2527

2628
from superset.common.query_object import QueryObject
2729
from superset.connectors.sqla.models import SqlaTable
@@ -672,6 +674,149 @@ def test_exec_post_processing_unknown_op_raises(app_context: None) -> None:
672674
assert "nonexistent_op" in str(excinfo.value)
673675

674676

677+
def _raise_value_error(df: DataFrame) -> DataFrame:
678+
"""A custom operation that fails from its own internals."""
679+
raise ValueError("a fault inside the operator's own code")
680+
681+
682+
@pytest.mark.parametrize(
683+
"operation,options,expected",
684+
[
685+
pytest.param(
686+
"diff",
687+
{"columns": {"y": "y"}, "periods": "not-an-int"},
688+
"periods must be an integer",
689+
id="diff-periods",
690+
),
691+
pytest.param(
692+
"rolling",
693+
{"rolling_type": "sum", "columns": {"y": "y"}, "window": "not-an-int"},
694+
"window must be an integer",
695+
id="rolling-window",
696+
),
697+
],
698+
)
699+
def test_exec_post_processing_reports_a_malformed_option_as_a_bad_request(
700+
operation: str, options: dict[str, Any], expected: str
701+
) -> None:
702+
"""
703+
A malformed option is a bad request, whatever pandas raises for it.
704+
705+
``ChartDataPostProcessingOperationSchema.options`` is an untyped
706+
``fields.Dict``, so no option is validated before it reaches pandas. Left
707+
unwrapped these reach ``app.errorhandler(Exception)``, which answers 500.
708+
"""
709+
query_object = QueryObject(
710+
row_limit=10,
711+
post_processing=[{"operation": operation, "options": options}],
712+
)
713+
714+
with pytest.raises(InvalidPostProcessingError) as excinfo:
715+
query_object.exec_post_processing(DataFrame({"y": [1.0, 2.0, 3.0]}))
716+
717+
assert expected in str(excinfo.value)
718+
assert f"`{operation}`" in str(excinfo.value)
719+
720+
721+
def test_exec_post_processing_names_a_column_the_result_does_not_have() -> None:
722+
"""
723+
A KeyError from a built-in operation names a column the options asked for.
724+
725+
``str(KeyError)`` is only the repr'd key, which on its own reads as a bare
726+
quoted string, so the message says what the key was.
727+
"""
728+
query_object = QueryObject(
729+
row_limit=10,
730+
post_processing=[
731+
{"operation": "rank", "options": {"metric": "does_not_exist"}}
732+
],
733+
)
734+
735+
with pytest.raises(InvalidPostProcessingError) as excinfo:
736+
query_object.exec_post_processing(DataFrame({"y": [1.0, 2.0, 3.0]}))
737+
738+
assert "does_not_exist" in str(excinfo.value)
739+
assert "not in the query result" in str(excinfo.value)
740+
assert "`rank`" in str(excinfo.value)
741+
742+
743+
@pytest.mark.parametrize(
744+
"raised",
745+
[
746+
pytest.param(
747+
AttributeError("'str' object has no attribute 'items'"), id="attr"
748+
),
749+
pytest.param(DataError("No numeric types to aggregate"), id="data"),
750+
pytest.param(TypeError("unsupported operand type(s)"), id="type"),
751+
],
752+
)
753+
def test_exec_post_processing_wraps_the_remaining_pandas_errors(
754+
raised: Exception,
755+
) -> None:
756+
"""The other types pandas raises for a bad option are bad requests too."""
757+
query_object = QueryObject(
758+
row_limit=10,
759+
post_processing=[{"operation": "rank", "options": {"metric": "y"}}],
760+
)
761+
762+
with (
763+
patch.object(pandas_postprocessing, "rank", side_effect=raised),
764+
pytest.raises(InvalidPostProcessingError) as excinfo,
765+
):
766+
query_object.exec_post_processing(DataFrame({"y": [1.0]}))
767+
768+
assert str(raised) in str(excinfo.value)
769+
770+
771+
def test_exec_post_processing_leaves_a_custom_operation_fault_unwrapped(
772+
app_context: None,
773+
) -> None:
774+
"""
775+
A failure inside a custom operation is a server fault, not a bad request.
776+
777+
An operation registered through ``EXTRA_PANDAS_POSTPROCESSING_OPS`` is the
778+
operator's own code, which this module cannot reason about, so its
779+
exceptions are left for the error handler rather than reported as the
780+
caller's mistake.
781+
"""
782+
query_object = QueryObject(
783+
row_limit=10,
784+
post_processing=[{"operation": "_raise_value_error"}],
785+
)
786+
787+
with (
788+
patch.dict(
789+
"superset.common.query_object.current_app.config",
790+
{"EXTRA_PANDAS_POSTPROCESSING_OPS": [_raise_value_error]},
791+
),
792+
pytest.raises(ValueError, match="operator's own code") as excinfo,
793+
):
794+
query_object.exec_post_processing(DataFrame({"y": [1.0]}))
795+
796+
assert not isinstance(excinfo.value, InvalidPostProcessingError)
797+
798+
799+
def test_exec_post_processing_leaves_a_missing_dependency_unwrapped() -> None:
800+
"""
801+
A missing optional dependency is a deployment matter, not a bad request.
802+
803+
``rolling`` with a ``win_type`` needs scipy, which is optional, so the
804+
ImportError pandas raises for it is deliberately not reported as 400.
805+
"""
806+
query_object = QueryObject(
807+
row_limit=10,
808+
post_processing=[{"operation": "rank", "options": {"metric": "y"}}],
809+
)
810+
811+
with (
812+
patch.object(
813+
pandas_postprocessing, "rank", side_effect=ImportError("no scipy")
814+
),
815+
pytest.raises(ImportError, match="no scipy"),
816+
):
817+
query_object.exec_post_processing(DataFrame({"y": [1.0]}))
818+
819+
675820
@pytest.mark.parametrize(
676821
"shadow_name",
677822
["build_extra_ops_map", "utils", "geography", "Any", "Callable", "annotations"],

0 commit comments

Comments
 (0)