This is an automated email from the ASF dual-hosted git repository.

villebro pushed a commit to branch 7.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 4879cf8f1e2dc3ffff8bb56b82a56e5b3d0e1730
Author: Dan Roscigno <[email protected]>
AuthorDate: Tue Nov 10 13:31:53 2026 -0500

    fix(mcp): disambiguate x_axis between column and axis styling (#42841)
    
    On 7.0 XYChartConfig.x also drops its x_axis alias, as master already had,
    so a styling-shaped x_axis reaches the axis field.
    
    Signed-off-by: DanRoscigno <[email protected]>
    Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
    Co-authored-by: Evan Rusackas <[email protected]>
    Co-authored-by: Amin Ghadersohi <[email protected]>
    
    (cherry picked from commit 842bad24791595f7399a1c6491235d380ede27c9)
---
 superset/mcp_service/chart/schemas.py              | 59 ++++++++++++++--
 .../mcp_service/chart/test_chart_schemas.py        | 79 ++++++++++++++++++++++
 2 files changed, 132 insertions(+), 6 deletions(-)

diff --git a/superset/mcp_service/chart/schemas.py 
b/superset/mcp_service/chart/schemas.py
index 93688f4c028..14f0ccdea82 100644
--- a/superset/mcp_service/chart/schemas.py
+++ b/superset/mcp_service/chart/schemas.py
@@ -853,6 +853,41 @@ class AxisConfig(UnknownFieldCheckMixin):
     format: str | None = Field(None, description="e.g. '$,.2f'", max_length=50)
 
 
+def _route_x_axis_key(data: Any, column_keys: tuple[str, ...]) -> Any:
+    """Route an ``x_axis`` payload to the column field or to axis styling.
+
+    Native ``form_data`` names the x-axis column ``x_axis``, and models that
+    accept it as a column alias also expose an ``x_axis`` styling field, so a
+    single input key would otherwise feed both. The payload's shape decides:
+    a bare string, or a non-empty mapping that names no styling field, is a
+    column reference and is moved to ``x``; anything else stays put and
+    configures the axis. Keying off the styling names rather than the column
+    names keeps a mistyped styling key ("sort_by") reported against
+    ``AxisConfig``, where the caller meant it, instead of against 
``ColumnRef``.
+    """
+    if not isinstance(data, dict) or "x_axis" not in data:
+        return data
+    value = data["x_axis"]
+    is_column_ref = isinstance(value, str) or (
+        isinstance(value, dict)
+        and bool(value)
+        and not set(value) & set(AxisConfig.model_fields)
+    )
+    if not is_column_ref:
+        return data
+    data = dict(data)
+    column = data.pop("x_axis")
+    if any(data.get(key) is not None for key in column_keys):
+        raise ValueError(
+            "'x_axis' was read as the x-axis column, but "
+            f"{' / '.join(repr(key) for key in column_keys)} names it too. "
+            "Pass the column once, and use 'x_axis' only for axis styling "
+            "(title, scale, format)."
+        )
+    data["x"] = {"name": column} if isinstance(column, str) else column
+    return data
+
+
 class LegendConfig(UnknownFieldCheckMixin):
     model_config = ConfigDict(extra="ignore")
 
@@ -1708,11 +1743,9 @@ class MixedTimeseriesChartConfig(BaseChartConfig):
     model_config = ConfigDict(extra="ignore", populate_by_name=True)
 
     chart_type: Literal["mixed_timeseries"] = "mixed_timeseries"
-    x: ColumnRef = Field(
-        ...,
-        description="Shared temporal X-axis column",
-        validation_alias=AliasChoices("x", "x_axis"),
-    )
+    # ``x_axis`` is also accepted for this field, but it arrives through
+    # ``disambiguate_x_axis`` rather than an alias -- see _route_x_axis_key.
+    x: ColumnRef = Field(..., description="Shared temporal X-axis column")
     time_grain: TimeGrain | None = Field(
         None,
         description="PT1H, P1D, P1W, P1M, P1Y",
@@ -1778,6 +1811,12 @@ class MixedTimeseriesChartConfig(BaseChartConfig):
     )
     row_limit: int = Field(10000, description="Max data points", ge=1, 
le=50000)
 
+    @model_validator(mode="before")
+    @classmethod
+    def disambiguate_x_axis(cls, data: Any) -> Any:
+        """Send an ``x_axis`` payload to ``x`` or to the styling field."""
+        return _route_x_axis_key(data, ("x",))
+
     @field_validator("group_by", "group_by_secondary", mode="before")
     @classmethod
     def wrap_single_group_by(cls, v: Any) -> Any:
@@ -2230,13 +2269,15 @@ class XYChartConfig(BaseChartConfig):
     model_config = ConfigDict(extra="ignore", populate_by_name=True)
 
     chart_type: Literal["xy"] = "xy"
+    # ``x_axis`` is also accepted for this field, but it arrives through
+    # ``disambiguate_x_axis`` rather than an alias -- see _route_x_axis_key.
     x: ColumnRef | None = Field(
         None,
         description=(
             "X-axis column. If omitted, defaults to the dataset's "
             "primary datetime column (main_dttm_col)."
         ),
-        validation_alias=AliasChoices("x", "x_axis", "x_column"),
+        validation_alias=AliasChoices("x", "x_column"),
     )
     y: List[ColumnRef] = Field(
         ...,
@@ -2315,6 +2356,12 @@ class XYChartConfig(BaseChartConfig):
         le=10000,
     )
 
+    @model_validator(mode="before")
+    @classmethod
+    def disambiguate_x_axis(cls, data: Any) -> Any:
+        """Send an ``x_axis`` payload to ``x`` or to the styling field."""
+        return _route_x_axis_key(data, ("x", "x_column"))
+
     @field_validator("group_by", mode="before")
     @classmethod
     def wrap_single_group_by(cls, v: Any) -> Any:
diff --git a/tests/unit_tests/mcp_service/chart/test_chart_schemas.py 
b/tests/unit_tests/mcp_service/chart/test_chart_schemas.py
index 629d90cc712..c047ef4538f 100644
--- a/tests/unit_tests/mcp_service/chart/test_chart_schemas.py
+++ b/tests/unit_tests/mcp_service/chart/test_chart_schemas.py
@@ -19,6 +19,8 @@
 Unit tests for MCP chart schema validation.
 """
 
+from typing import Any
+
 import pytest
 from pydantic import ValidationError
 
@@ -744,6 +746,83 @@ class TestUnknownFieldDetection:
             AxisConfig.model_validate({"title": "State", "sort_by": "metric"})
 
 
+class TestXAxisRouting:
+    """``x_axis`` names the x column and the axis styling; both must work.
+
+    Strict nested field checking makes the overlap load-bearing: a payload
+    routed to the wrong model is rejected rather than quietly half-applied.
+    """
+
+    XY_BASE = {"chart_type": "xy", "y": [{"name": "sales", "aggregate": 
"SUM"}]}
+    MIXED_BASE = {
+        "chart_type": "mixed_timeseries",
+        "metrics": [{"name": "revenue", "aggregate": "SUM"}],
+        "metrics_b": [{"name": "orders", "aggregate": "COUNT"}],
+    }
+
+    @pytest.mark.parametrize(
+        "value", [{"name": "category"}, {"column_name": "category"}, 
"category"]
+    )
+    def test_column_shaped_x_axis_becomes_the_x_column(self, value: Any) -> 
None:
+        config = XYChartConfig.model_validate({**self.XY_BASE, "x_axis": 
value})
+        assert config.x is not None
+        assert config.x.name == "category"
+        assert config.x_axis is None
+
+    def test_styling_shaped_x_axis_configures_the_axis(self) -> None:
+        config = XYChartConfig.model_validate(
+            {**self.XY_BASE, "x_axis": {"title": "State", "scale": "log"}}
+        )
+        assert config.x is None
+        assert config.x_axis is not None
+        assert config.x_axis.title == "State"
+        assert config.x_axis.scale == "log"
+
+    def test_column_and_styling_both_supplied(self) -> None:
+        config = XYChartConfig.model_validate(
+            {**self.XY_BASE, "x": {"name": "category"}, "x_axis": {"title": 
"State"}}
+        )
+        assert config.x is not None
+        assert config.x.name == "category"
+        assert config.x_axis is not None
+        assert config.x_axis.title == "State"
+
+    def test_column_named_twice_is_rejected(self) -> None:
+        """``x`` and a column-shaped ``x_axis`` together are ambiguous."""
+        with pytest.raises(ValidationError, match="Pass the column once"):
+            XYChartConfig.model_validate(
+                {**self.XY_BASE, "x": {"name": "a"}, "x_axis": {"name": "b"}}
+            )
+
+    def test_mistyped_styling_key_reported_against_the_axis(self) -> None:
+        """A styling payload stays a styling payload, typo and all."""
+        with pytest.raises(ValidationError, match="Unknown field 'sort_by'"):
+            XYChartConfig.model_validate(
+                {**self.XY_BASE, "x_axis": {"title": "State", "sort_by": 
"metric"}}
+            )
+
+    def test_mistyped_column_key_reported_against_the_column(self) -> None:
+        with pytest.raises(ValidationError, match="did you mean 'aggregate'"):
+            XYChartConfig.model_validate(
+                {**self.XY_BASE, "x_axis": {"name": "category", "aggregat": 
"SUM"}}
+            )
+
+    def test_mixed_timeseries_x_axis_becomes_the_x_column(self) -> None:
+        config = MixedTimeseriesChartConfig.model_validate(
+            {**self.MIXED_BASE, "x_axis": {"name": "ds"}}
+        )
+        assert config.x.name == "ds"
+        assert config.x_axis is None
+
+    def test_mixed_timeseries_x_axis_styling(self) -> None:
+        config = MixedTimeseriesChartConfig.model_validate(
+            {**self.MIXED_BASE, "x": {"name": "ds"}, "x_axis": {"title": 
"Date"}}
+        )
+        assert config.x.name == "ds"
+        assert config.x_axis is not None
+        assert config.x_axis.title == "Date"
+
+
 class TestColumnRefSavedMetric:
     """Test ColumnRef saved_metric support."""
 

Reply via email to