You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "gkneighb (via GitHub)" <gi...@apache.org> on 2026/08/27 02:59:30 UTC

[PR] feat(mcp): sankey chart type plugin [superset]

gkneighb opened a new pull request, #43573:
URL: https://github.com/apache/superset/pull/43573

   ### SUMMARY
   
   Adds a `generate_chart` MCP plugin for the **sankey** chart type (`viz_type: sankey_v2`), so the MCP `generate_chart` tool can produce sankey flow diagrams. Sankey is a shipped Superset viz type that had no MCP plugin; this closes that gap.
   
   The plugin mirrors the frontend Sankey `buildQuery` contract: a `source` and a `target` column define the edges of the flow diagram (the query groups by both) and one `metric` weights each edge. When `sort_by_metric` is set (the frontend default), edges are ordered by the metric descending.
   
   Follows the established plugin pattern (`pie`/`funnel`/`gauge`/`treemap`/`heatmap`/`radar`/`bubble`/`waterfall`) — a config schema, a `map_*_config` mapper, a plugin class, and registration:
   
   - **`SankeyChartConfig`** — `source`, `target`, and `metric` required; optional `sort_by_metric`, `row_limit`, `filters`, `color_scheme`. Added to the `ChartConfig` discriminated union and the `get_chart_type_schema` adapters. `source`/`target` may not be `saved_metric`/`sql_expression` (node dimensions, not metrics).
   - **`map_sankey_config`** — maps the config to `form_data`; saved metrics pass through as a bare name string, ad-hoc metrics as SIMPLE/SQL adhoc objects.
   - **`SankeyChartPlugin`** — registered in the plugin registry. `sankey_v2` was absent from the recommendation category map, so this adds it (its own `sankey` category).
   
   The field set is intentionally minimal (core query contract).
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   
   N/A — backend/MCP only, no UI change.
   
   ### TESTING INSTRUCTIONS
   
   `pytest tests/unit_tests/mcp_service/chart/test_sankey_chart.py` — 18 unit tests cover schema validation (three required fields, `source`/`target` not-a-metric, extra-field rejection), `ChartConfig` union dispatch, `form_data` mapping (source/target/metric/sort/filters/saved-metric), and registry integration (registration, `resolve_viz_type`, `display_name`, `pre_validate`, recommendation category).
   
   To exercise end-to-end: call the `generate_chart` MCP tool with
   `{"chart_type": "sankey_v2", "source": {"name": "from_stage"}, "target": {"name": "to_stage"}, "metric": {"name": "users", "aggregate": "SUM"}}`.
   
   ### ADDITIONAL INFORMATION
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [x] Introduces new feature or API
   - [ ] Removes existing feature or API
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43573:
URL: https://github.com/apache/superset/pull/43573#discussion_r3871556184


##########
superset/mcp_service/chart/schemas.py:
##########
@@ -1045,6 +1045,63 @@ def reject_sql_expression_on_dimensions(self) -> "PieChartConfig":
         return self
 
 
+class SankeyChartConfig(BaseChartConfig):
+    """Config for sankey charts (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and a
+    ``target`` column define the edges of the flow diagram and one ``metric``
+    weights each edge. When ``sort_by_metric`` is set the query orders by the
+    metric descending.
+    """
+
+    model_config = ConfigDict(extra="ignore", populate_by_name=True)
+
+    chart_type: Literal["sankey_v2"] = "sankey_v2"
+    source: ColumnRef = Field(
+        ...,
+        description="Column used as the source (origin) node of each edge",
+    )
+    target: ColumnRef = Field(
+        ...,
+        description="Column used as the target (destination) node of each edge",
+    )
+    metric: ColumnRef = Field(
+        ...,
+        description="Metric weighting each edge (use aggregate e.g. SUM, "
+        "COUNT for ad-hoc, or set saved_metric=True for a saved dataset metric)",
+    )
+    sort_by_metric: bool = Field(
+        True,
+        description="Order edges by the metric descending (frontend default)",
+    )
+    row_limit: int = Field(10000, description="Max edges queried", ge=1, le=100000)
+    filters: List[FilterConfig] | None = Field(
+        None,
+        description="Structured filters (column/op/value). "
+        "Do NOT use adhoc_filters or raw SQL expressions.",
+    )
+    color_scheme: str | None = Field(
+        None,
+        description=(
+            "Superset color scheme ID (e.g. 'supersetColors', 'lyftColors', "
+            "'googleCategory10c', 'd3Category10'). Defaults to 'supersetColors'."
+        ),
+        max_length=100,
+    )
+
+    @model_validator(mode="after")
+    def reject_metric_style_nodes(self) -> "SankeyChartConfig":
+        """source and target are node dimensions, not metrics."""
+        for col, name in ((self.source, "source"), (self.target, "target")):
+            _reject_sql_expression_on_dimension(col, name)
+            if col and col.saved_metric:
+                raise ValueError(
+                    f"{name} cannot use saved_metric=True; "
+                    "saved metrics belong in the 'metric' field"
+                )

Review Comment:
   **Suggestion:** Dimension validation rejects `sql_expression` and `saved_metric`, but it does not reject `aggregate` on `source` or `target`. Such a configuration passes schema and dataset aggregation validation for compatible aggregates, then `map_sankey_config` discards the aggregate and emits only the raw column name, silently changing the requested Sankey semantics. Reject aggregated source/target references during validation. [type error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Sankey charts can show flows grouped by raw nodes despite requested source/target aggregation.
   - ⚠️ `generate_chart` accepts invalid dimension configuration without feedback.
   - ⚠️ Saved charts preserve misleading configuration semantics in generated form data.
   ```
   </details>
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=7c7ba0f482d74d56845c307d6bc0984f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=7c7ba0f482d74d56845c307d6bc0984f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/schemas.py
   **Line:** 1095:1101
   **Comment:**
   	*Type Error: Dimension validation rejects `sql_expression` and `saved_metric`, but it does not reject `aggregate` on `source` or `target`. Such a configuration passes schema and dataset aggregation validation for compatible aggregates, then `map_sankey_config` discards the aggregate and emits only the raw column name, silently changing the requested Sankey semantics. Reject aggregated source/target references during validation.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43573&comment_hash=31f06ffe57b8507f719dd383d2f2c07be96e344a76975468ca5744e2abbc43ff&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43573&comment_hash=31f06ffe57b8507f719dd383d2f2c07be96e344a76975468ca5744e2abbc43ff&reaction=dislike'>👎</a>



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5440483222

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5946817311

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43573:
URL: https://github.com/apache/superset/pull/43573#discussion_r3871564263


##########
superset/mcp_service/chart/chart_utils.py:
##########
@@ -1017,6 +1018,27 @@ def map_pie_config(config: PieChartConfig) -> Dict[str, Any]:
     return form_data
 
 
+def map_sankey_config(config: SankeyChartConfig) -> Dict[str, Any]:
+    """Map sankey config to Superset form_data (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and
+    ``target`` column form the edges (the query groups by both) and one
+    ``metric`` weights each edge. When ``sort_by_metric`` is set the query
+    orders by the metric descending.
+    """
+    form_data: Dict[str, Any] = {
+        "viz_type": "sankey_v2",
+        "source": config.source.name,
+        "target": config.target.name,
+        "metric": create_metric_object(config.metric),
+        "sort_by_metric": config.sort_by_metric,

Review Comment:
   **Suggestion:** `sort_by_metric` is preserved in form data, but the MCP query builder does not translate it into an `orderby` clause; the frontend-only `buildQuery` implementation is not invoked by the MCP generation path. As a result, requests using the default `sort_by_metric=True` do not actually order edges by descending metric. Add the corresponding order-by information when constructing the MCP query. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ MCP Sankey previews ignore default metric ordering.
   - ⚠️ Largest flows may not appear first.
   - ⚠️ Row-limited results can omit higher-weight edges.
   ```
   </details>
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c754d80198d54e6a92dce3d12f7343e8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=c754d80198d54e6a92dce3d12f7343e8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/chart_utils.py
   **Line:** 1034:1034
   **Comment:**
   	*Logic Error: `sort_by_metric` is preserved in form data, but the MCP query builder does not translate it into an `orderby` clause; the frontend-only `buildQuery` implementation is not invoked by the MCP generation path. As a result, requests using the default `sort_by_metric=True` do not actually order edges by descending metric. Add the corresponding order-by information when constructing the MCP query.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43573&comment_hash=83397ff62d2d5078a099d6695f7202f23ef61c5736cda2270081d419d5caf822&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43573&comment_hash=83397ff62d2d5078a099d6695f7202f23ef61c5736cda2270081d419d5caf822&reaction=dislike'>👎</a>



##########
superset/mcp_service/chart/chart_utils.py:
##########
@@ -1017,6 +1018,27 @@ def map_pie_config(config: PieChartConfig) -> Dict[str, Any]:
     return form_data
 
 
+def map_sankey_config(config: SankeyChartConfig) -> Dict[str, Any]:
+    """Map sankey config to Superset form_data (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and
+    ``target`` column form the edges (the query groups by both) and one
+    ``metric`` weights each edge. When ``sort_by_metric`` is set the query
+    orders by the metric descending.
+    """
+    form_data: Dict[str, Any] = {
+        "viz_type": "sankey_v2",
+        "source": config.source.name,
+        "target": config.target.name,
+        "metric": create_metric_object(config.metric),

Review Comment:
   **Suggestion:** The MCP query builder reads grouping columns from `groupby`, but this mapper only emits `source` and `target`; unlike the frontend `buildQuery`, the backend MCP path does not derive `groupby` from those fields. Generated Sankey queries therefore aggregate the metric over the entire dataset instead of producing one weighted edge per source/target pair. Include both node columns in the query grouping data or add equivalent Sankey-specific handling to the MCP query builder. [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ MCP Sankey previews aggregate all edges together.
   - ❌ Generated Sankey flow relationships are lost.
   - ⚠️ Compile validation checks the wrong query shape.
   ```
   </details>
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=0743db826c4e43aa8ae8513ff409ccc0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=0743db826c4e43aa8ae8513ff409ccc0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/chart_utils.py
   **Line:** 1031:1033
   **Comment:**
   	*Api Mismatch: The MCP query builder reads grouping columns from `groupby`, but this mapper only emits `source` and `target`; unlike the frontend `buildQuery`, the backend MCP path does not derive `groupby` from those fields. Generated Sankey queries therefore aggregate the metric over the entire dataset instead of producing one weighted edge per source/target pair. Include both node columns in the query grouping data or add equivalent Sankey-specific handling to the MCP query builder.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43573&comment_hash=94224237b0a17afc2712d669ea37ebe4f476e05e6f5aa752972d2300e223be06&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43573&comment_hash=94224237b0a17afc2712d669ea37ebe4f476e05e6f5aa752972d2300e223be06&reaction=dislike'>👎</a>



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #43573:
URL: https://github.com/apache/superset/pull/43573#discussion_r4130332314


##########
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(exclude_unset=True)
+
+        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

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Duplicated metric normalization</b></div>
   <div id="fix">
   
   The metric-normalization chain (sql_expression → skip, saved_metric → `get_canonical_metric_name`, else `get_canonical_column_name`) is copied verbatim from `pie.py`/`treemap.py` and appears in 13 sibling plugins; `BaseChartPlugin` hosts no shared helper. Extract one helper (e.g. on `DatasetValidator` beside `get_canonical_*`) and call it here, so the next canonicalization fix lands once instead of 13 times.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #d00ad7</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
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

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Unannotated test locals</b></div>
   <div id="fix">
   
   Locals such as `cfg` (line 50), `config`, `form_data`, `queries`, and `orderby` are assigned without type annotations throughout the file. BITO rule 13153 asks for explicit annotations on test-file locals even when inferable; `Any` is already imported for this purpose.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #d00ad7</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
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:

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing test docstrings</b></div>
   <div id="fix">
   
   16 of the 19 test functions (e.g. `test_basic_sankey_config`, `test_group_by_and_order_by`, `test_pre_validate_missing_fields`) have no docstring; only `test_sankey_source_rejects_aggregate` and the two query-builder tests do. BITO rule 12148 requires a docstring on every newly added test function documenting scenario and expected outcome.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #d00ad7</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
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"
+
+    def test_sankey_saved_metric_maps_to_name_string(self) -> None:
+        config = SankeyChartConfig(
+            chart_type="sankey_v2",
+            source={"name": "from_stage"},
+            target={"name": "to_stage"},
+            metric={"name": "flow_volume", "saved_metric": True},
+        )
+        assert map_sankey_config(config)["metric"] == "flow_volume"
+
+
+class TestSankeySourceTargetReachQueryBuilders:
+    """The emitted form_data must group by the edge's node columns.
+
+    ``source``/``target`` are the frontend Sankey buildQuery field names; the
+    backend query builders derive grouping columns from ``groupby`` and have no
+    alias for them (unlike ``entity``/``series``). Without an explicit
+    ``groupby`` the query aggregates the whole dataset into a single row instead
+    of one row per edge, so assert against the real consumers rather than the
+    emitted key alone.
+    """
+
+    @staticmethod
+    def _form_data() -> dict[str, Any]:
+        return map_sankey_config(
+            SankeyChartConfig(
+                chart_type="sankey_v2",
+                source={"name": "from_stage"},
+                target={"name": "to_stage"},
+                metric={"name": "users", "aggregate": "SUM"},
+            )
+        )
+
+    def test_resolve_groupby_returns_the_node_columns(self) -> None:
+        """The ``get_chart_data`` path groups by source and target."""
+        assert resolve_groupby(self._form_data()) == ["from_stage", "to_stage"]
+
+    def test_columns_from_form_data_returns_the_node_columns(self) -> None:
+        """The chart-preview path groups by source and target."""
+        assert columns_from_form_data(self._form_data()) == [
+            "from_stage",
+            "to_stage",
+        ]
+
+
+class TestSankeyQueryContext:
+    """The built query must GROUP BY source+target and ORDER BY the metric.
+
+    Both transforms live in the frontend buildQuery; the MCP path rebuilds the
+    query dict directly, so they must be re-derived or the query collapses to a
+    single unordered aggregate row.
+    """
+
+    def test_group_by_and_order_by(self, monkeypatch) -> None:

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Unannotated fixture parameter</b></div>
   <div id="fix">
   
   `monkeypatch` is a pytest fixture but is the only unannotated parameter in the file. BITO rule 12101 requires explicit annotations on fixture-injected parameters; `pytest.MonkeyPatch` is available in the repo's pytest 7.4.0.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #d00ad7</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/mcp_service/chart/schemas.py:
##########
@@ -1673,6 +1673,64 @@ def record_implicit_metric_aggregate(self) -> "BubbleChartConfig":
         return self
 
 
+class SankeyChartConfig(BaseChartConfig):
+    """Config for sankey charts (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and a
+    ``target`` column define the edges of the flow diagram and one ``metric``
+    weights each edge. When ``sort_by_metric`` is set the query orders by the
+    metric descending.
+    """
+
+    model_config = ConfigDict(extra="ignore", populate_by_name=True)
+
+    chart_type: Literal["sankey_v2"] = "sankey_v2"
+    source: ColumnRef = Field(
+        ...,
+        description="Column used as the source (origin) node of each edge",
+    )
+    target: ColumnRef = Field(
+        ...,
+        description="Column used as the target (destination) node of each edge",
+    )
+    metric: ColumnRef = Field(
+        ...,
+        description="Metric weighting each edge (use aggregate e.g. SUM, "
+        "COUNT for ad-hoc, or set saved_metric=True for a saved dataset metric)",
+    )

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing implicit-aggregate recording</b></div>
   <div id="fix">
   
   Unlike `BubbleChartConfig.record_implicit_metric_aggregate`, no validator records an implicit SUM for a bare `metric` ref. `create_metric_object` defaults to SUM at map time, while `DatasetValidator._validate_aggregations` skips refs without `aggregate` — so SUM over a text column fails in the database instead of with a clear validation message. Mirror the Bubble validator.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #d00ad7</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/mcp_service/chart/schemas.py:
##########
@@ -1673,6 +1673,64 @@ def record_implicit_metric_aggregate(self) -> "BubbleChartConfig":
         return self
 
 
+class SankeyChartConfig(BaseChartConfig):
+    """Config for sankey charts (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and a
+    ``target`` column define the edges of the flow diagram and one ``metric``
+    weights each edge. When ``sort_by_metric`` is set the query orders by the
+    metric descending.
+    """
+
+    model_config = ConfigDict(extra="ignore", populate_by_name=True)
+
+    chart_type: Literal["sankey_v2"] = "sankey_v2"
+    source: ColumnRef = Field(
+        ...,
+        description="Column used as the source (origin) node of each edge",
+    )
+    target: ColumnRef = Field(
+        ...,
+        description="Column used as the target (destination) node of each edge",
+    )
+    metric: ColumnRef = Field(
+        ...,
+        description="Metric weighting each edge (use aggregate e.g. SUM, "
+        "COUNT for ad-hoc, or set saved_metric=True for a saved dataset metric)",
+    )
+    sort_by_metric: bool = Field(
+        True,
+        description="Order edges by the metric descending (frontend default)",
+    )
+    row_limit: int = Field(10000, description="Max edges queried", ge=1, le=100000)
+    filters: List[FilterConfig] | None = Field(
+        None,
+        description="Structured filters (column/op/value). "
+        "Do NOT use adhoc_filters or raw SQL expressions.",
+    )
+    color_scheme: str | None = Field(
+        None,
+        description=(
+            "Superset color scheme ID (e.g. 'supersetColors', 'lyftColors', "
+            "'googleCategory10c', 'd3Category10'). Defaults to 'supersetColors'."
+        ),
+        max_length=100,
+    )
+
+    @model_validator(mode="after")
+    def reject_metric_style_nodes(self) -> "SankeyChartConfig":
+        """source and target are node dimensions, not metrics."""
+        for col, name in ((self.source, "source"), (self.target, "target")):
+            _reject_sql_expression_on_dimension(col, name)
+            if col and col.is_metric:

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Dead truthiness guard</b></div>
   <div id="fix">
   
   `source`/`target` are required, non-optional `ColumnRef` fields, and Pydantic v2 `BaseModel` instances are always truthy (no `__bool__`/`__len__`), so `col` in `col and col.is_metric` is always true — a dead guard. Sibling `BubbleChartConfig.reject_metric_style_dimensions` omits it; drop the `col and` conjunct for consistency.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #d00ad7</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5884656819

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5739788221

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5464454550

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5882845084

   @rusackas Done at `c47db173bb` — you were right that it's real rather than a style nag, and your trace through `merge_chart_form_data` matches what I measured.
   
   `sankey.py` now uses `model_dump(exclude_unset=True)` like `pie.py`, with a regression test beside the existing pie twin in `test_chart_utils.py` (`test_merge_sankey_preserves_omitted_defaults`). It runs the config through `DatasetValidator.normalize_column_names` first, exactly as `update_chart` does, then asserts an omitted `color_scheme`/`row_limit` survives while explicitly supplied values still win. It fails on the previous head and passes now.
   
   Since the same shape could be anywhere, I audited every registered plugin rather than just this one:
   
   | plugin | state |
   | --- | --- |
   | sankey, funnel, heatmap | had it — fixed on their own PRs |
   | radar | had it — fixed earlier on #43571 |
   | bubble | had it on master — **#44618** |
   | gantt | **not** affected — it captures `model_fields_set` before the dump and restores it after, which is equivalent |
   | the other 13 | already passed `exclude_unset=True` |
   
   So gantt looked guilty to a grep but is fine; I verified it by running `normalize_column_refs` and confirming `row_limit` stays out of `model_fields_set`.
   
   Thanks for tracing it instead of forwarding the bot thread — that's what made it obvious it was worth chasing across the family.
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5482629711

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5438908712

   <!-- Bito Reply -->
   The issue is correct. The `SankeyChartConfig` validator currently only checks for `sql_expression` and `saved_metric` on `source` and `target` dimensions, but it fails to reject the `aggregate` field, which leads to silent semantic changes in the generated Sankey configuration. To resolve this, update the `reject_metric_style_nodes` validator in `superset/mcp_service/chart/schemas.py` to also check for and reject the `aggregate` field on `source` and `target` columns.
   
   **superset/mcp_service/chart/schemas.py**
   ```
   @model_validator(mode="after")
       def reject_metric_style_nodes(self) -> "SankeyChartConfig":
           """source and target are node dimensions, not metrics."""
           for col, name in ((self.source, "source"), (self.target, "target")):
               _reject_sql_expression_on_dimension(col, name)
               if col and (col.saved_metric or col.aggregate):
                   raise ValueError(
                       f"{name} cannot use saved_metric=True or aggregate; "
                       "saved metrics and aggregates belong in the 'metric' field"
                   )
           return self
   ```


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5806312881

   Rebased onto current master, since bubble (#43572) merged on 2026-09-21 and re-conflicted this branch.
   
   Also proactively fixed a defect a reviewer caught on the sibling PRs (#43570, #43571): my earlier Gantt-cascade rebase left a duplicated line in the `get_chart_type_schema` docstring, so clients received `interactive_pivot.` twice in the live tool description. It was present on this branch too and is now gone; I audited all four branches in this family and all are clean.
   
   This head also picks up `43fee87672`, which fixes the unrelated `test_base_restore_version_command` failures (#44436) that reddened the previous run.
   
   No change to the plugin itself. Re-verified at this head: `_CHART_TYPE_ADAPTERS` 16 == `_CHART_EXAMPLES` 16 with nothing missing, this type plus `bubble_v2` and `gantt` all registered, the chart's own test file passing, ruff/mypy/pylint clean on the committed tree, and `git merge-tree` clean against master.
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5747030146

   Heads-up for anyone reviewing the red check here: the three failing checks are **not** from this diff.
   
   All three come from the same six tests in `tests/unit_tests/commands/test_base_restore_version_command.py`, which fail on current master for every PR built against it — including PRs from other authors (e.g. #44435). This branch touches nothing under `superset/commands/`. Filed with the root cause and a suggested fix as #44436.
   
   Everything else on this run is green (61 passed, 3 failed, 0 cancelled), and the branch is rebased onto master and mergeable.
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5496889029

   @gkneighb Thanks for fixing the original Sankey grouping and shared-builder ordering issues. A fresh Red Hat product-completeness pass at head `6a86a0a3` found the typed foundation is still incomplete in the end-to-end MCP paths. Could you please address or explicitly coordinate these before we count Sankey support as complete?
   
   1. **Unsaved query + previews:** `generate_chart(save_chart=False)` still bypasses the Sankey-aware shared query builder, so limited previews can use unordered edges. Saved previews fall through to scatter and unsaved previews to an incomplete bar; add a shared Sankey representation using source, target, and the resolved saved/SIMPLE/SQL metric label, with all-row validation—or return a clear unsupported-format error rather than a false chart.
   2. **Native round-trip and updates:** adapt returned native string dimensions, derived `groupby`, and saved/SIMPLE/SQL metric objects back into `SankeyChartConfig`. Preserve omitted `sort_by_metric`, `row_limit`, color, filters, and UI state across immediate, preview-first, and cached updates; explicit values/empty filters should still override.
   3. **Sankey semantics:** require finite numeric metric output (including saved/SQL metrics), reject canonically identical or case-ambiguous source/target roles, and normalize casing before every tool path maps form data.
   4. **Discovery:** add a real Sankey recommendation candidate for a two-categorical-plus-numeric result, not only the current-viz exclusion mapping.
   5. **Product-path tests:** cover generate/update/update-preview/get-data plus saved/form-data-key and unsaved previews, including error/empty/malformed envelopes and row-limit ordering.
   
   I ran the 21 Sankey tests and the full MCP chart suite (1,388 passed) plus adversarial reproductions; these gaps remain despite green CI. Shared builder, normalization, and query-error work in #43737 should be reused/rebased rather than duplicated, while retaining this PR’s Sankey ordering behavior. I did not modify or push to your branch.
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5780116445

   This one also seems to need a rebase, sorry things keep churning. Holler if you want a hand on any of these PRs.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5433827373

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/43573?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `43.20988%` with `46 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 57.43%. Comparing base ([`1c66b71`](https://app.codecov.io/gh/apache/superset/commit/1c66b71e232271011ec540a601288e5f99fcfa2f?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`4a45a88`](https://app.codecov.io/gh/apache/superset/commit/4a45a88dce088c91d13eead516e3957f179a4551?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/43573?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [superset/mcp\_service/chart/plugins/sankey.py](https://app.codecov.io/gh/apache/superset/pull/43573?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fchart%2Fplugins%2Fsankey.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvY2hhcnQvcGx1Z2lucy9zYW5rZXkucHk=) | 34.54% | [36 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/43573?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/mcp\_service/chart/chart\_utils.py](https://app.codecov.io/gh/apache/superset/pull/43573?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fchart%2Fchart_utils.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvY2hhcnQvY2hhcnRfdXRpbHMucHk=) | 28.57% | [5 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/43573?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/mcp\_service/chart/schemas.py](https://app.codecov.io/gh/apache/superset/pull/43573?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fchart%2Fschemas.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvY2hhcnQvc2NoZW1hcy5weQ==) | 70.58% | [5 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/43573?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   > :exclamation:  There is a different number of reports uploaded between BASE (1c66b71) and HEAD (4a45a88). Click for more details.
   > 
   > <details><summary>HEAD has 19 uploads less than BASE</summary>
   >
   >| Flag | BASE (1c66b71) | HEAD (4a45a88) |
   >|------|------|------|
   >|hive|3|1|
   >|python|17|2|
   >|presto|3|1|
   ></details>
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff             @@
   ##           master   #43573       +/-   ##
   ===========================================
   - Coverage   79.10%   57.43%   -21.68%     
   ===========================================
     Files        2878     2879        +1     
     Lines      165637   165718       +81     
     Branches    38295    38309       +14     
   ===========================================
   - Hits       131029    95181    -35848     
   - Misses      32122    69642    +37520     
   + Partials     2486      895     -1591     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/43573/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [hive](https://app.codecov.io/gh/apache/superset/pull/43573/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `37.96% <43.20%> (+<0.01%)` | :arrow_up: |
   | [mysql](https://app.codecov.io/gh/apache/superset/pull/43573/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [postgres](https://app.codecov.io/gh/apache/superset/pull/43573/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/43573/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.87% <43.20%> (+<0.01%)` | :arrow_up: |
   | [python](https://app.codecov.io/gh/apache/superset/pull/43573/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.93% <43.20%> (-43.75%)` | :arrow_down: |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/43573/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [unit](https://app.codecov.io/gh/apache/superset/pull/43573/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/43573?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5457666697

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | cdcfaa65f00c16cf2e5f163a4fae3622b29e4009 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a91f52e601b7b00085c2870 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-43573--superset-docs-preview.netlify.app](https://deploy-preview-43573--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQzNTczLS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.kLCApBbhUf68gVmRWr99Rl3ol-RyASt6VOKu4H8Le7E)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   |<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#q1YqKMrPLShRslJS0lFKKkrMS84AstNSE0v0c5MLdIsT87JTK3ULckrTM_OAKlJSC3LyKz1TgGrMEi0N00yNUs0MDJPMkwwMDCxMk40szA2UagE) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-43573--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5574551254

   Re-reviewed `bf5628cb86ad82aef28adf26b0c37e7a84211fcd` against refreshed base `87f138cc`. The shared-builder grouping/descending metric ordering remains correct, but the material gaps in [the prior request](https://github.com/apache/superset/pull/43573#issuecomment-5496889029) remain:
   
   - **Unsaved ordering and previews:** with `row_limit=1`, the shared builder emits metric-descending `orderby`, while `generate_preview_from_form_data` emits `orderby=[]` ([query construction](https://github.com/apache/superset/blob/bf5628cb86ad82aef28adf26b0c37e7a84211fcd/superset/mcp_service/chart/preview_utils.py#L101-L112)). The same edge data produces an unsaved Vega-Lite bar with only a color encoding and a saved-preview scatter fallback—not a weighted flow. Please use a faithful representation or an explicit unsupported-format error.
   - **Round-trip/update preservation:** passing mapper-produced native form data into `GenerateChartRequest` fails for saved/SIMPLE/SQL metrics. An immediate update with omitted controls resets `sort_by_metric=False`, `row_limit=37`, and `lyftColors` to `True`, `10000`, and `supersetColors`, and drops existing filters/UI state ([payload construction](https://github.com/apache/superset/blob/bf5628cb86ad82aef28adf26b0c37e7a84211fcd/superset/mcp_service/chart/tool/update_chart.py#L232-L251)). Preview-first merging also resets those three controls; cached preview updates still lack general Sankey preservation.
   - **Validation/casing:** mocked successful query envelopes containing string, infinity, or NaN weights all pass `_compile_chart`. `source=Node,target=node` is accepted and normalizes to `Node,Node`, including with both case-distinct columns present. `update_chart_preview` still maps before normalization. These need explicit finite-weight and unambiguous-role checks across tool paths.
   - **Recommendations:** two string dimensions plus one numeric column still returns only `bar chart`/`pie chart`; the added current-viz category does not create a Sankey candidate.
   
   Verification: **21 Sankey tests passed; the full MCP chart unit suite passed (1,408 tests)**, plus targeted mocked reproductions above. Sankey-specific tests remain confined to the schema/mapper/registry test file; public generate/update/update-preview/get-data and saved/cached/unsaved preview regressions are still needed, including error/empty/malformed envelopes. No live-app verification was available. No contributor code was modified or pushed.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-6029757928

   @rusackas Following up on the CI question from your sankey review — the rebase is done on all four and the picture turned out different from what either of us expected. One correction first: **the byte budget isn't failing.** All four now fail exactly one test, `test_dispatchers_do_not_branch_on_registered_chart_types` from #44746, and nothing else:
   
   | PR | what the guard flags |
   | --- | --- |
   | #43567 funnel | `preview_utils: {'funnel': generate_funnel_vega_lite_preview}` |
   | #43570 heatmap | `chart_helpers: viz_type == 'heatmap_v2'` |
   | #43571 radar | `get_chart_data: _VIZ_CATEGORY` → `radar` |
   | #43573 sankey | `get_chart_data: _VIZ_CATEGORY` → `sankey_v2` |
   
   **The mechanism is worth stating plainly, because it isn't "these PRs add bad code."** The guard flags dispatcher branches keyed on *registered* chart types. Registering a type is therefore enough to turn pre-existing code into a violation.
   
   #43567 is the clean illustration. `_FALLBACK_VEGA_RENDERERS = {"funnel": generate_funnel_vega_lite_preview}` is **master's line**, added by #44746 itself at `preview_utils.py:1382`. It's legal today only because `funnel` isn't registered, so it isn't in `_LEGACY_TYPE_BRANCHES`. The moment #43567 registers the plugin, master's own dict becomes the violation. My diff doesn't touch that file.
   
   #43570 is the mirror image: the flagged `viz_type == 'heatmap_v2'` is a line **I wrote during this rebase**, adopting your `with_x_axis_column()` helper to keep the heatmap x-axis reaching `GROUP BY`. Correct for the pre-#44746 shape, illegal by construction now.
   
   So all four need the same thing — move the per-type behavior into the plugin hooks the new contract provides, so no shared dispatcher names the type. That's a real port, not a line edit, and I don't want to guess at your intent on two points:
   
   1. **Was this anticipated?** `preview_utils` on master already mentions `funnel` (3×), `radar` and `sankey`. If #44746 was written with these four in mind, you may already have a shape in mind for how they should land — I'd rather implement that than invent a parallel one.
   2. **Who should do it?** Happy to port all four onto the contract. But if it's cleaner for whoever holds #44746 to absorb them — four approved plugins is a decent forcing function for the hooks — that's fine by me and probably faster. Parking them until the contract settles is also a reasonable answer.
   
   Separately, your non-blocking nit on this PR is valid: `SankeyChartConfig` has no `record_implicit_metric_aggregate`, so a bare metric on a text column fails at the database instead of returning the clean `invalid_aggregation`. I'll fold that in with whatever port shape you pick rather than pushing it standalone.
   
   All four are rebased, mergeable, and green apart from that one test.
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43573:
URL: https://github.com/apache/superset/pull/43573#discussion_r4162639828


##########
superset/mcp_service/chart/schemas.py:
##########
@@ -1045,6 +1045,63 @@ def reject_sql_expression_on_dimensions(self) -> "PieChartConfig":
         return self
 
 
+class SankeyChartConfig(BaseChartConfig):
+    """Config for sankey charts (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and a
+    ``target`` column define the edges of the flow diagram and one ``metric``
+    weights each edge. When ``sort_by_metric`` is set the query orders by the
+    metric descending.
+    """
+
+    model_config = ConfigDict(extra="ignore", populate_by_name=True)
+
+    chart_type: Literal["sankey_v2"] = "sankey_v2"
+    source: ColumnRef = Field(
+        ...,
+        description="Column used as the source (origin) node of each edge",
+    )
+    target: ColumnRef = Field(
+        ...,
+        description="Column used as the target (destination) node of each edge",
+    )
+    metric: ColumnRef = Field(
+        ...,
+        description="Metric weighting each edge (use aggregate e.g. SUM, "
+        "COUNT for ad-hoc, or set saved_metric=True for a saved dataset metric)",
+    )
+    sort_by_metric: bool = Field(
+        True,
+        description="Order edges by the metric descending (frontend default)",
+    )
+    row_limit: int = Field(10000, description="Max edges queried", ge=1, le=100000)
+    filters: List[FilterConfig] | None = Field(
+        None,
+        description="Structured filters (column/op/value). "
+        "Do NOT use adhoc_filters or raw SQL expressions.",
+    )
+    color_scheme: str | None = Field(
+        None,
+        description=(
+            "Superset color scheme ID (e.g. 'supersetColors', 'lyftColors', "
+            "'googleCategory10c', 'd3Category10'). Defaults to 'supersetColors'."
+        ),
+        max_length=100,
+    )
+
+    @model_validator(mode="after")
+    def reject_metric_style_nodes(self) -> "SankeyChartConfig":
+        """source and target are node dimensions, not metrics."""
+        for col, name in ((self.source, "source"), (self.target, "target")):
+            _reject_sql_expression_on_dimension(col, name)
+            if col and col.saved_metric:
+                raise ValueError(
+                    f"{name} cannot use saved_metric=True; "
+                    "saved metrics belong in the 'metric' field"
+                )

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `6886650`.
   
   The Sankey dimension validator now rejects any source or target where `col.is_metric` is true, covering aggregated and saved-metric references while allowing only plain node columns.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



##########
superset/mcp_service/chart/chart_utils.py:
##########
@@ -1017,6 +1018,27 @@ def map_pie_config(config: PieChartConfig) -> Dict[str, Any]:
     return form_data
 
 
+def map_sankey_config(config: SankeyChartConfig) -> Dict[str, Any]:
+    """Map sankey config to Superset form_data (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and
+    ``target`` column form the edges (the query groups by both) and one
+    ``metric`` weights each edge. When ``sort_by_metric`` is set the query
+    orders by the metric descending.
+    """
+    form_data: Dict[str, Any] = {
+        "viz_type": "sankey_v2",
+        "source": config.source.name,
+        "target": config.target.name,
+        "metric": create_metric_object(config.metric),

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `6886650`.
   
   `map_sankey_config` now emits `groupby` containing both `config.source.name` and `config.target.name`, ensuring MCP queries aggregate one weighted row per source/target pair.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5458991374

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5433797395

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5565835302

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #43573:
URL: https://github.com/apache/superset/pull/43573#discussion_r4090355952


##########
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:

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>fields_set inflation resets controls</b></div>
   <div id="fix">
   
   `normalize_column_refs` returns `SankeyChartConfig.model_validate(config.model_dump())`, so every field lands in `model_fields_set`. On the update path (`update_chart.py` → `DatasetValidator.normalize_column_names` → `merge_chart_form_data`), the `color_scheme`/`row_limit` preservation guard (`field not in fields_set`) never fires, so updates omitting these controls silently reset them to mapper defaults. Use `model_dump(exclude_unset=True)` as `pie.py` does.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #218fdd</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-6198437124

   ## CodeAnt PR Risk: Low Risk
   
   - The PR appears safe to merge; the Sankey configuration and query mapping address the identified grouping and metric-ordering concerns.
   - Tests verify that queries group by both node columns and sort descending by the metric when enabled.
   
   **Assessed commit:** `482bc18ea05b`


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5463607162

   @aminghadersohi — correction on my round-2 fix: you're right that the `orderby` I'd stashed in `form_data` was a no-op. `_build_single_query_dict` never reads a top-level `orderby` (only the `deck_*` path does), which your funnel review made clear. Fixed properly in `b5682e877e`:
   
   - Removed the no-op `form_data["orderby"]` emission from `map_sankey_config`.
   - Emit `orderby` in the shared `_build_single_query_dict` when `sort_by_metric` is set, so the metric ordering actually reaches the query (this covers pie/funnel/treemap by the same path).
   - Replaced the mapper-level assertion with a query-context test: `build_query_dicts_from_form_data(...)` now yields `columns=['from_stage','to_stage']` **and** a descending metric `orderby`.
   
   The GROUP BY fix from round 2 stands; this closes the ordering half.
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43573:
URL: https://github.com/apache/superset/pull/43573#discussion_r4089160550


##########
superset/mcp_service/chart/schemas.py:
##########
@@ -1045,6 +1045,63 @@ def reject_sql_expression_on_dimensions(self) -> "PieChartConfig":
         return self
 
 
+class SankeyChartConfig(BaseChartConfig):
+    """Config for sankey charts (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and a
+    ``target`` column define the edges of the flow diagram and one ``metric``
+    weights each edge. When ``sort_by_metric`` is set the query orders by the
+    metric descending.
+    """
+
+    model_config = ConfigDict(extra="ignore", populate_by_name=True)
+
+    chart_type: Literal["sankey_v2"] = "sankey_v2"
+    source: ColumnRef = Field(
+        ...,
+        description="Column used as the source (origin) node of each edge",
+    )
+    target: ColumnRef = Field(
+        ...,
+        description="Column used as the target (destination) node of each edge",
+    )
+    metric: ColumnRef = Field(
+        ...,
+        description="Metric weighting each edge (use aggregate e.g. SUM, "
+        "COUNT for ad-hoc, or set saved_metric=True for a saved dataset metric)",
+    )
+    sort_by_metric: bool = Field(
+        True,
+        description="Order edges by the metric descending (frontend default)",
+    )
+    row_limit: int = Field(10000, description="Max edges queried", ge=1, le=100000)
+    filters: List[FilterConfig] | None = Field(
+        None,
+        description="Structured filters (column/op/value). "
+        "Do NOT use adhoc_filters or raw SQL expressions.",
+    )
+    color_scheme: str | None = Field(
+        None,
+        description=(
+            "Superset color scheme ID (e.g. 'supersetColors', 'lyftColors', "
+            "'googleCategory10c', 'd3Category10'). Defaults to 'supersetColors'."
+        ),
+        max_length=100,
+    )
+
+    @model_validator(mode="after")
+    def reject_metric_style_nodes(self) -> "SankeyChartConfig":
+        """source and target are node dimensions, not metrics."""
+        for col, name in ((self.source, "source"), (self.target, "target")):
+            _reject_sql_expression_on_dimension(col, name)
+            if col and col.saved_metric:
+                raise ValueError(
+                    f"{name} cannot use saved_metric=True; "
+                    "saved metrics belong in the 'metric' field"
+                )

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `073e59e`.
   
   Source and target are now rejected when `col.is_metric` is true, covering aggregated or saved-metric references and requiring plain node columns.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



##########
superset/mcp_service/chart/chart_utils.py:
##########
@@ -1017,6 +1018,27 @@ def map_pie_config(config: PieChartConfig) -> Dict[str, Any]:
     return form_data
 
 
+def map_sankey_config(config: SankeyChartConfig) -> Dict[str, Any]:
+    """Map sankey config to Superset form_data (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and
+    ``target`` column form the edges (the query groups by both) and one
+    ``metric`` weights each edge. When ``sort_by_metric`` is set the query
+    orders by the metric descending.
+    """
+    form_data: Dict[str, Any] = {
+        "viz_type": "sankey_v2",
+        "source": config.source.name,
+        "target": config.target.name,
+        "metric": create_metric_object(config.metric),

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `073e59e`.
   
   The Sankey form data now explicitly includes `groupby` containing both the source and target column names.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43573:
URL: https://github.com/apache/superset/pull/43573#discussion_r4129207890


##########
superset/mcp_service/chart/schemas.py:
##########
@@ -1045,6 +1045,63 @@ def reject_sql_expression_on_dimensions(self) -> "PieChartConfig":
         return self
 
 
+class SankeyChartConfig(BaseChartConfig):
+    """Config for sankey charts (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and a
+    ``target`` column define the edges of the flow diagram and one ``metric``
+    weights each edge. When ``sort_by_metric`` is set the query orders by the
+    metric descending.
+    """
+
+    model_config = ConfigDict(extra="ignore", populate_by_name=True)
+
+    chart_type: Literal["sankey_v2"] = "sankey_v2"
+    source: ColumnRef = Field(
+        ...,
+        description="Column used as the source (origin) node of each edge",
+    )
+    target: ColumnRef = Field(
+        ...,
+        description="Column used as the target (destination) node of each edge",
+    )
+    metric: ColumnRef = Field(
+        ...,
+        description="Metric weighting each edge (use aggregate e.g. SUM, "
+        "COUNT for ad-hoc, or set saved_metric=True for a saved dataset metric)",
+    )
+    sort_by_metric: bool = Field(
+        True,
+        description="Order edges by the metric descending (frontend default)",
+    )
+    row_limit: int = Field(10000, description="Max edges queried", ge=1, le=100000)
+    filters: List[FilterConfig] | None = Field(
+        None,
+        description="Structured filters (column/op/value). "
+        "Do NOT use adhoc_filters or raw SQL expressions.",
+    )
+    color_scheme: str | None = Field(
+        None,
+        description=(
+            "Superset color scheme ID (e.g. 'supersetColors', 'lyftColors', "
+            "'googleCategory10c', 'd3Category10'). Defaults to 'supersetColors'."
+        ),
+        max_length=100,
+    )
+
+    @model_validator(mode="after")
+    def reject_metric_style_nodes(self) -> "SankeyChartConfig":
+        """source and target are node dimensions, not metrics."""
+        for col, name in ((self.source, "source"), (self.target, "target")):
+            _reject_sql_expression_on_dimension(col, name)
+            if col and col.saved_metric:
+                raise ValueError(
+                    f"{name} cannot use saved_metric=True; "
+                    "saved metrics belong in the 'metric' field"
+                )

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `c47db17`.
   
   Source and target are now rejected when `col.is_metric` is true, covering aggregated or saved-metric references and requiring plain node columns.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



##########
superset/mcp_service/chart/chart_utils.py:
##########
@@ -1017,6 +1018,27 @@ def map_pie_config(config: PieChartConfig) -> Dict[str, Any]:
     return form_data
 
 
+def map_sankey_config(config: SankeyChartConfig) -> Dict[str, Any]:
+    """Map sankey config to Superset form_data (viz_type ``sankey_v2``).
+
+    Matches the frontend Sankey buildQuery contract: a ``source`` and
+    ``target`` column form the edges (the query groups by both) and one
+    ``metric`` weights each edge. When ``sort_by_metric`` is set the query
+    orders by the metric descending.
+    """
+    form_data: Dict[str, Any] = {
+        "viz_type": "sankey_v2",
+        "source": config.source.name,
+        "target": config.target.name,
+        "metric": create_metric_object(config.metric),

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `c47db17`.
   
   The Sankey form data now explicitly includes `groupby` containing both the source and target column names.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5808221462

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5612425046

   Fresh re-review at `eb72811b549c` confirms progress since `bf5628cb`: unsaved compile/preview queries now use metric-descending ordering; cached-preview mapping normalizes column case first; omitted filters/UI state survive updates, and explicit empty filters clear them. Ambiguous non-exact column references and failed-status query envelopes are also handled.
   
   The remaining gaps from [the previous review](https://github.com/apache/superset/pull/43573#issuecomment-5574551254) are reproducible:
   
   - **Preview fidelity:** the same Sankey edge produces an unsaved Vega-Lite bar with only a color encoding, while saved previews still take the scatter fallback. Neither represents weighted flow; please provide a faithful representation or an explicit unsupported-format error.
   - **Round-trip/updates:** mapper-produced native form data still fails `GenerateChartRequest` with `Unknown field 'groupby'` for saved/SIMPLE/SQL metrics. Immediate and cached-preview reproductions reset omitted `sort_by_metric=False`, `row_limit=37`, and `color_scheme='lyftColors'` to `True`, `10000`, and `supersetColors`. The [shared merge](https://github.com/apache/superset/blob/eb72811b549c0972e93199093a3c20a1a803b960/superset/mcp_service/chart/chart_utils.py#L675-L721) only protects omitted mapped controls for Gauge, not Sankey.
   - **Validation:** string/NaN/infinite weights still pass compilation for saved/SIMPLE/SQL metrics, including an invalid second row. `source=Node,target=node` with one physical `Node` column still normalizes to duplicate `Node,Node` roles. A malformed `data: 'malformed'` envelope also reports compile success. The [result validator](https://github.com/apache/superset/blob/eb72811b549c0972e93199093a3c20a1a803b960/superset/mcp_service/chart/query_result.py#L125-L135) remains Gauge-only.
   - **Recommendations:** two string dimensions plus one numeric column still yields only `bar chart`/`pie chart`, not Sankey.
   
   Verification: chart unit suite **1,583 passed, 1 skipped**, plus targeted mocked reproductions including the cached-preview tool. Sankey-specific tests remain confined to schema/mapper/registry coverage. GitHub reports mergeable/clean, with 63 checks passing and 12 skipped. No live app was available; no contributor code was changed or pushed.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): sankey chart type plugin [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43573:
URL: https://github.com/apache/superset/pull/43573#issuecomment-5614145929

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org