Copilot commented on code in PR #43573:
URL: https://github.com/apache/superset/pull/43573#discussion_r3890440806
##########
superset/mcp_service/chart/chart_helpers.py:
##########
@@ -489,6 +489,13 @@ def _build_single_query_dict(
qd["row_limit"] = effective_row_limit
if order_desc is not None:
qd["order_desc"] = order_desc
+ # sort_by_metric charts (pie/funnel/treemap/sankey) order by the metric
+ # descending. buildQuery derives this on the frontend; the MCP path builds
+ # the query dict directly and never reads a top-level form_data['orderby'],
+ # so translate the flag here or a row_limit truncates an unordered result
+ # (dropping the heaviest rows rather than the top-N by the metric).
Review Comment:
The comment mentions funnel/treemap, but the MCP chart plugins/schemas in
this module currently only expose `sort_by_metric` for pie and sankey. This
makes the comment misleading for future maintainers; please update it to match
the actual supported chart types (or phrase it generically).
##########
superset/mcp_service/chart/plugins/sankey.py:
##########
@@ -0,0 +1,148 @@
+# 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.
+
+"""Sankey chart type plugin."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, ClassVar
+
+from superset.mcp_service.chart.chart_utils import (
+ _sankey_chart_what,
+ _summarize_filters,
+ map_sankey_config,
+)
+from superset.mcp_service.chart.plugin import BaseChartPlugin
+from superset.mcp_service.chart.schemas import ColumnRef, SankeyChartConfig
+from superset.mcp_service.chart.validation.dataset_validator import
DatasetValidator
+from superset.mcp_service.common.error_schemas import ChartGenerationError
+
+
+class SankeyChartPlugin(BaseChartPlugin):
+ """Plugin for sankey chart type."""
+
+ chart_type = "sankey_v2"
+ display_name = "Sankey Diagram"
+ native_viz_types: ClassVar[Mapping[str, str]] = {
+ "sankey_v2": "Sankey Diagram",
+ }
+
+ def pre_validate(
+ self,
+ config: dict[str, Any],
+ ) -> ChartGenerationError | None:
+ missing_fields = []
+
+ if "source" not in config:
+ missing_fields.append("'source' (origin node column)")
+ if "target" not in config:
+ missing_fields.append("'target' (destination node column)")
+ if "metric" not in config:
+ missing_fields.append("'metric' (edge weight)")
+
+ if missing_fields:
+ return ChartGenerationError(
+ error_type="missing_sankey_fields",
+ message=(
+ f"Sankey chart missing required fields: {',
'.join(missing_fields)}"
+ ),
+ details=(
+ "Sankey diagrams draw weighted flows from a source node to
"
+ "a target node; the metric sets each edge's width"
+ ),
+ suggestions=[
+ "Add 'source': {'name': 'from_stage'}",
+ "Add 'target': {'name': 'to_stage'}",
+ "Add 'metric': {'name': 'users', 'aggregate': 'SUM'}",
+ "Example: {'chart_type': 'sankey_v2', "
+ "'source': {'name': 'from_stage'}, "
+ "'target': {'name': 'to_stage'}, "
+ "'metric': {'name': 'users', 'aggregate': 'SUM'}}",
+ ],
+ error_code="MISSING_SANKEY_FIELDS",
+ )
+
+ return None
+
+ def extract_column_refs(self, config: Any) -> list[ColumnRef]:
+ if not isinstance(config, SankeyChartConfig):
+ return []
+ refs: list[ColumnRef] = [config.source, config.target, config.metric]
+ if config.filters:
+ for f in config.filters:
+ refs.append(ColumnRef(name=f.column))
+ return refs
+
+ def to_form_data(
+ self, config: Any, dataset_id: int | str | None = None
+ ) -> dict[str, Any]:
+ return map_sankey_config(config)
+
+ def generate_name(self, config: Any, dataset_name: str | None = None) ->
str:
+ what = _sankey_chart_what(config)
+ context = _summarize_filters(config.filters)
+ return self._with_context(what, context)
+
+ def resolve_viz_type(self, config: Any) -> str:
+ return "sankey_v2"
+
+ def normalize_column_refs(self, config: Any, dataset_context: Any) -> Any:
+ config_dict = config.model_dump()
+
+ for key in ("source", "target"):
+ col = config_dict.get(key)
+ if col and not col.get("sql_expression") and not
col.get("saved_metric"):
+ col["name"] = DatasetValidator.get_canonical_column_name(
+ col["name"], dataset_context
+ )
+ if config_dict.get("metric"):
+ if config_dict["metric"].get("sql_expression"):
+ pass
+ elif config_dict["metric"].get("saved_metric"):
+ config_dict["metric"]["name"] = (
+ DatasetValidator.get_canonical_metric_name(
+ config_dict["metric"]["name"], dataset_context
+ )
+ )
+ else:
+ config_dict["metric"]["name"] = (
+ DatasetValidator.get_canonical_column_name(
+ config_dict["metric"]["name"], dataset_context
+ )
+ )
+ DatasetValidator.normalize_filters(config_dict, dataset_context)
+ return SankeyChartConfig.model_validate(config_dict)
+
+ def schema_error_hint(self) -> ChartGenerationError | None:
+ return ChartGenerationError(
+ error_type="sankey_validation_error",
+ message="Sankey chart configuration validation failed",
+ details=(
+ "The sankey chart configuration is missing required "
+ "fields or has invalid structure"
+ ),
+ suggestions=[
+ "Ensure 'source' and 'target' each have a 'name'",
+ "Ensure 'metric' field has 'name' and 'aggregate'",
+ "Example: {'chart_type': 'sankey_v2', "
+ "'source': {'name': 'from_stage'}, "
+ "'target': {'name': 'to_stage'}, "
+ "'metric': {'name': 'users', 'aggregate': 'SUM'}}",
+ ],
Review Comment:
`schema_error_hint()` suggests that `metric` must include an `aggregate`,
but the schema also allows saved metrics (`saved_metric=True`) and SQL metrics
(`sql_expression` + `label`). As written, the suggestions can mislead callers
into providing invalid or unnecessary fields.
##########
tests/unit_tests/mcp_service/chart/test_sankey_chart.py:
##########
@@ -0,0 +1,270 @@
+# 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.
+
+"""Tests for the sankey chart type plugin.
+
+Schema validation, form_data mapping (matching the frontend Sankey buildQuery
+contract for viz_type ``sankey_v2`` — a ``source`` and ``target`` column plus
+one ``metric`` weighting each edge), and registry integration.
+"""
+
+from typing import Any
+
+import pytest
+from pydantic import TypeAdapter, ValidationError
+
+from superset.common.form_data_query_context import columns_from_form_data
+from superset.mcp_service.chart.chart_helpers import resolve_groupby
+from superset.mcp_service.chart.chart_utils import map_sankey_config
+from superset.mcp_service.chart.schemas import ChartConfig, SankeyChartConfig
+
+
+class TestSankeyChartConfigSchema:
+ """SankeyChartConfig schema validation."""
+
+ def test_basic_sankey_config(self) -> None:
+ config = SankeyChartConfig(
+ chart_type="sankey_v2",
+ source={"name": "from_stage"},
+ target={"name": "to_stage"},
+ metric={"name": "users", "aggregate": "SUM"},
+ )
+ assert config.source.name == "from_stage"
+ assert config.target.name == "to_stage"
+ assert config.sort_by_metric is True # shared control default
+
+ @pytest.mark.parametrize("missing", ["source", "target", "metric"])
+ def test_sankey_missing_required(self, missing: str) -> None:
+ cfg = {
+ "chart_type": "sankey_v2",
+ "source": {"name": "from_stage"},
+ "target": {"name": "to_stage"},
+ "metric": {"name": "users", "aggregate": "SUM"},
+ }
+ del cfg[missing]
+ with pytest.raises(ValidationError):
+ SankeyChartConfig(**cfg)
+
+ def test_sankey_rejects_extra_fields(self) -> None:
+ with pytest.raises(ValidationError):
+ SankeyChartConfig(
+ chart_type="sankey_v2",
+ source={"name": "from_stage"},
+ target={"name": "to_stage"},
+ metric={"name": "users", "aggregate": "SUM"},
+ bogus=1,
+ )
+
+ def test_sankey_source_rejects_saved_metric(self) -> None:
+ with pytest.raises(ValidationError):
+ SankeyChartConfig(
+ chart_type="sankey_v2",
+ source={"name": "count", "saved_metric": True},
+ target={"name": "to_stage"},
+ metric={"name": "users", "aggregate": "SUM"},
+ )
+
+ def test_sankey_target_rejects_saved_metric(self) -> None:
+ with pytest.raises(ValidationError):
+ SankeyChartConfig(
+ chart_type="sankey_v2",
+ source={"name": "from_stage"},
+ target={"name": "count", "saved_metric": True},
+ metric={"name": "users", "aggregate": "SUM"},
+ )
+
+ def test_sankey_source_rejects_aggregate(self) -> None:
+ """An aggregate makes source metric-like; source is a node
dimension."""
+ with pytest.raises(ValidationError):
+ SankeyChartConfig(
+ chart_type="sankey_v2",
+ source={"name": "amount", "aggregate": "SUM"},
+ target={"name": "to_stage"},
+ metric={"name": "users", "aggregate": "SUM"},
+ )
+
+ def test_sankey_target_rejects_aggregate(self) -> None:
+ with pytest.raises(ValidationError):
+ SankeyChartConfig(
+ chart_type="sankey_v2",
+ source={"name": "from_stage"},
+ target={"name": "amount", "aggregate": "SUM"},
+ metric={"name": "users", "aggregate": "SUM"},
+ )
+
+ def test_chart_config_union_dispatches_sankey(self) -> None:
+ config = TypeAdapter(ChartConfig).validate_python(
+ {
+ "chart_type": "sankey_v2",
+ "source": {"name": "from_stage"},
+ "target": {"name": "to_stage"},
+ "metric": {"name": "users", "aggregate": "SUM"},
+ }
+ )
+ assert isinstance(config, SankeyChartConfig)
+
+
+class TestMapSankeyConfig:
+ """form_data mapping must match the frontend Sankey buildQuery."""
+
+ def test_basic_sankey_form_data(self) -> None:
+ config = SankeyChartConfig(
+ chart_type="sankey_v2",
+ source={"name": "from_stage"},
+ target={"name": "to_stage"},
+ metric={"name": "users", "aggregate": "SUM"},
+ )
+ form_data = map_sankey_config(config)
+ assert form_data["viz_type"] == "sankey_v2"
+ assert form_data["source"] == "from_stage"
+ assert form_data["target"] == "to_stage"
+ assert form_data["groupby"] == ["from_stage", "to_stage"]
+ assert form_data["metric"]["label"] == "SUM(users)"
+ assert form_data["sort_by_metric"] is True
+ # orderby is applied by the query-dict builder, not stashed in
form_data
+ # (a top-level form_data['orderby'] is a no-op on the MCP path)
+ assert "orderby" not in form_data
+
+ def test_sankey_form_data_with_filters_and_no_sort(self) -> None:
+ config = SankeyChartConfig(
+ chart_type="sankey_v2",
+ source={"name": "from_stage"},
+ target={"name": "to_stage"},
+ metric={"name": "users", "aggregate": "SUM"},
+ sort_by_metric=False,
+ filters=[{"column": "year", "op": "=", "value": 2026}],
+ )
+ form_data = map_sankey_config(config)
+ assert form_data["sort_by_metric"] is False
+ assert "orderby" not in form_data # no metric ordering when unset
+ assert form_data["adhoc_filters"], "filters must map to adhoc_filters"
Review Comment:
This test covers that `orderby` is not stored in `form_data` when
`sort_by_metric=False`, but it doesn't assert the more important behavior
introduced in `_build_single_query_dict`: that the built query dict also omits
`orderby` in this case. Adding that assertion would prevent regressions where
`sort_by_metric=False` still orders results.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]