codeant-ai-for-open-source[bot] commented on code in PR #43367: URL: https://github.com/apache/superset/pull/43367#discussion_r3824229566
########## superset/mcp_service/dashboard/layout_validation.py: ########## @@ -0,0 +1,140 @@ +# 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. + +"""Validation for dashboard layouts supplied through MCP tools.""" + +from __future__ import annotations + +from collections.abc import Collection +from typing import Any + +_ROOT_ID = "ROOT_ID" +_GRID_ID = "GRID_ID" +_HEADER_ID = "HEADER_ID" +_CHART_TYPE = "CHART" +_CONTAINER_TYPES = {"GRID", "TABS"} + + +def validate_dashboard_layout( # noqa: C901 + layout: dict[str, Any], expected_chart_ids: Collection[int] +) -> str | None: + """Return an error when an MCP layout replacement is unsafe to persist. + + Superset renders only components reachable from ``ROOT_ID``. It separately + indexes every chart component in ``position_json``, including unreachable + ones, so an orphaned chart can suppress hydration's missing-chart fallback + while remaining invisible. Validate graph reachability and parent paths, + then require the layout to contain exactly the dashboard's associated + charts before allowing a full replacement. + + ``HEADER_ID`` is dashboard metadata rather than a rendered tree child. + Superset also retains an empty, detached ``GRID_ID`` when top-level tabs are + used; both are allowed as explicit reserved-node exceptions. + """ + root = layout.get(_ROOT_ID) + if not isinstance(root, dict) or root.get("type") != "ROOT": + return "Layout must contain a ROOT_ID component with type ROOT." + + root_children = root.get("children", []) + if not isinstance(root_children, list) or not all( + isinstance(child_id, str) for child_id in root_children + ): + return "ROOT_ID.children must be a list of component IDs." + if len(root_children) > 1: + return "ROOT_ID may contain at most one GRID or TABS component." + if root_children: + root_child = layout.get(root_children[0]) + if not isinstance(root_child, dict) or root_child.get("type") not in ( + _CONTAINER_TYPES + ): + return "ROOT_ID's child must be a GRID or TABS component." + + visited: set[str] = set() + visiting: set[str] = set() + reachable_chart_ids: set[int] = set() + + def visit( # noqa: C901 + component_id: str, ancestors: list[str] + ) -> str | None: + if component_id in visiting: + return f"Layout contains a cycle at {component_id}." + if component_id in visited: + return f"Layout component {component_id} has more than one parent." + + component = layout.get(component_id) + if not isinstance(component, dict): + return f"Layout references missing component {component_id}." + if component.get("id") != component_id: + return f"Layout component {component_id} must have the same id value." + if component_id == _ROOT_ID: + if component.get("parents", []) not in ([], None): + return "ROOT_ID must not have parents." + elif component.get("parents") != ancestors: + return f"Layout component {component_id} has inconsistent parents." + + children = component.get("children", []) + if not isinstance(children, list) or not all( + isinstance(child_id, str) for child_id in children + ): + return f"Layout component {component_id}.children must be a list." + + if component.get("type") == _CHART_TYPE: + meta = component.get("meta") + chart_id = meta.get("chartId") if isinstance(meta, dict) else None + if not isinstance(chart_id, int) or isinstance(chart_id, bool): + return f"Chart component {component_id} must have an integer chartId." Review Comment: **Suggestion:** The validator rejects `meta.chartId` values stored as strings, even though existing dashboard layouts may legitimately contain string representations and the sibling chart-removal tool explicitly supports both integer and string IDs. Updating such a legacy or hand-edited dashboard will therefore return `InvalidDashboardLayout` despite the layout referring to the correct associated charts. Normalize numeric strings or compare both representations before rejecting the layout. [api mismatch] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Full-layout updates reject imported or hand-edited dashboards with string chart IDs. - ⚠️ Users cannot make otherwise valid incremental layout changes through MCP. ``` </details> [](https://docs.codeant.ai/cli/resolve-pr-comments-skill) <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/mcp_service/dashboard/layout_validation.py **Line:** 98:99 **Comment:** *Api Mismatch: The validator rejects `meta.chartId` values stored as strings, even though existing dashboard layouts may legitimately contain string representations and the sibling chart-removal tool explicitly supports both integer and string IDs. Updating such a legacy or hand-edited dashboard will therefore return `InvalidDashboardLayout` despite the layout referring to the correct associated charts. Normalize numeric strings or compare both representations before rejecting the layout. 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%2F43367&comment_hash=d553a5def6cb491ba68a301bff8f29646595b16a09aa717992742d637088700a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43367&comment_hash=d553a5def6cb491ba68a301bff8f29646595b16a09aa717992742d637088700a&reaction=dislike'>👎</a> ########## superset/mcp_service/dashboard/layout_validation.py: ########## @@ -0,0 +1,140 @@ +# 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. + +"""Validation for dashboard layouts supplied through MCP tools.""" + +from __future__ import annotations + +from collections.abc import Collection +from typing import Any + +_ROOT_ID = "ROOT_ID" +_GRID_ID = "GRID_ID" +_HEADER_ID = "HEADER_ID" +_CHART_TYPE = "CHART" +_CONTAINER_TYPES = {"GRID", "TABS"} + + +def validate_dashboard_layout( # noqa: C901 + layout: dict[str, Any], expected_chart_ids: Collection[int] +) -> str | None: + """Return an error when an MCP layout replacement is unsafe to persist. + + Superset renders only components reachable from ``ROOT_ID``. It separately + indexes every chart component in ``position_json``, including unreachable + ones, so an orphaned chart can suppress hydration's missing-chart fallback + while remaining invisible. Validate graph reachability and parent paths, + then require the layout to contain exactly the dashboard's associated + charts before allowing a full replacement. + + ``HEADER_ID`` is dashboard metadata rather than a rendered tree child. + Superset also retains an empty, detached ``GRID_ID`` when top-level tabs are + used; both are allowed as explicit reserved-node exceptions. + """ + root = layout.get(_ROOT_ID) + if not isinstance(root, dict) or root.get("type") != "ROOT": + return "Layout must contain a ROOT_ID component with type ROOT." + + root_children = root.get("children", []) + if not isinstance(root_children, list) or not all( + isinstance(child_id, str) for child_id in root_children + ): + return "ROOT_ID.children must be a list of component IDs." + if len(root_children) > 1: + return "ROOT_ID may contain at most one GRID or TABS component." + if root_children: + root_child = layout.get(root_children[0]) + if not isinstance(root_child, dict) or root_child.get("type") not in ( + _CONTAINER_TYPES + ): + return "ROOT_ID's child must be a GRID or TABS component." + + visited: set[str] = set() + visiting: set[str] = set() + reachable_chart_ids: set[int] = set() + + def visit( # noqa: C901 + component_id: str, ancestors: list[str] + ) -> str | None: + if component_id in visiting: + return f"Layout contains a cycle at {component_id}." + if component_id in visited: + return f"Layout component {component_id} has more than one parent." + + component = layout.get(component_id) + if not isinstance(component, dict): + return f"Layout references missing component {component_id}." + if component.get("id") != component_id: + return f"Layout component {component_id} must have the same id value." + if component_id == _ROOT_ID: + if component.get("parents", []) not in ([], None): + return "ROOT_ID must not have parents." + elif component.get("parents") != ancestors: + return f"Layout component {component_id} has inconsistent parents." + + children = component.get("children", []) + if not isinstance(children, list) or not all( + isinstance(child_id, str) for child_id in children + ): + return f"Layout component {component_id}.children must be a list." + + if component.get("type") == _CHART_TYPE: + meta = component.get("meta") + chart_id = meta.get("chartId") if isinstance(meta, dict) else None + if not isinstance(chart_id, int) or isinstance(chart_id, bool): + return f"Chart component {component_id} must have an integer chartId." + if children: + return f"Chart component {component_id} cannot have children." + reachable_chart_ids.add(chart_id) + + visiting.add(component_id) + for child_id in children: + if error := visit(child_id, [*ancestors, component_id]): Review Comment: **Suggestion:** The recursive walk has no depth limit and does not handle `RecursionError`. A caller can submit a deeply nested layout that causes the validator to exceed Python's recursion limit, so `update_dashboard` fails before returning its structured validation error and can tie up or disrupt the request worker. Validate with an iterative traversal or enforce a bounded nesting depth. [security] <details> <summary><b>Severity Level:</b> Minor 🧹</summary> ```mdx - ⚠️ Deep layout validation can abort an MCP request unexpectedly. - ⚠️ A malicious authorized caller can consume request-worker work with oversized nesting. ``` </details> [](https://docs.codeant.ai/cli/resolve-pr-comments-skill) <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/mcp_service/dashboard/layout_validation.py **Line:** 104:106 **Comment:** *Security: The recursive walk has no depth limit and does not handle `RecursionError`. A caller can submit a deeply nested layout that causes the validator to exceed Python's recursion limit, so `update_dashboard` fails before returning its structured validation error and can tie up or disrupt the request worker. Validate with an iterative traversal or enforce a bounded nesting depth. 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%2F43367&comment_hash=1cc0505493a3ef4647e919754fb93b771ff1cca42b8c3f826d2efc9213cc1fae&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43367&comment_hash=1cc0505493a3ef4647e919754fb93b771ff1cca42b8c3f826d2efc9213cc1fae&reaction=dislike'>👎</a> ########## superset/mcp_service/dashboard/schemas.py: ########## @@ -798,9 +798,10 @@ class UpdateDashboardRequest(BaseModel): None, description=( "Optional replacement layout (Superset's position_json dict). " - "When set, fully replaces the existing layout. Get the current " - "layout via ``get_dashboard_info`` first if you want to make " - "incremental changes." + "When set, fully replaces the existing layout and must keep every " + "dashboard chart reachable from ROOT_ID, with consistent children " + "and parents. Get the current layout via ``get_dashboard_layout`` " + "first if you want to make incremental changes." Review Comment: **Suggestion:** The request description instructs callers to retrieve the current layout with `get_dashboard_layout` before making incremental changes, but that tool returns only parsed tabs and chart positions and omits the raw component tree, including component IDs, children, parents, and metadata needed by this full-replacement validator. An agent following this guidance cannot reliably construct a valid replacement. Either expose the raw layout through the discovery tool or change the description to direct callers to an API that provides the complete `position_json`. [api mismatch] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ MCP agents cannot reliably perform documented incremental layout edits. - ⚠️ Full replacements require unavailable component-tree metadata. ``` </details> [](https://docs.codeant.ai/cli/resolve-pr-comments-skill) <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/mcp_service/dashboard/schemas.py **Line:** 800:804 **Comment:** *Api Mismatch: The request description instructs callers to retrieve the current layout with `get_dashboard_layout` before making incremental changes, but that tool returns only parsed tabs and chart positions and omits the raw component tree, including component IDs, children, parents, and metadata needed by this full-replacement validator. An agent following this guidance cannot reliably construct a valid replacement. Either expose the raw layout through the discovery tool or change the description to direct callers to an API that provides the complete `position_json`. 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%2F43367&comment_hash=d8f6f09ed3ff6f3b69cf457f476ef7085eac7b02e0dcdc3e1dd848dc36c9387c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43367&comment_hash=d8f6f09ed3ff6f3b69cf457f476ef7085eac7b02e0dcdc3e1dd848dc36c9387c&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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
