codeant-ai-for-open-source[bot] commented on code in PR #39922: URL: https://github.com/apache/superset/pull/39922#discussion_r3501401437
########## superset/mcp_service/chart/plugins/table.py: ########## @@ -0,0 +1,136 @@ +# 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. + +"""Table 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 ( + _summarize_filters, + _table_chart_what, + map_table_config, +) +from superset.mcp_service.chart.plugin import BaseChartPlugin +from superset.mcp_service.chart.schemas import ColumnRef, TableChartConfig +from superset.mcp_service.chart.validation.dataset_validator import DatasetValidator +from superset.mcp_service.common.error_schemas import ChartGenerationError + + +class TableChartPlugin(BaseChartPlugin): + """Plugin for table chart type.""" + + chart_type = "table" + display_name = "Table" + native_viz_types: ClassVar[Mapping[str, str]] = { + "table": "Table", + "ag-grid-table": "Interactive Table", + } + + def pre_validate( + self, + config: dict[str, Any], + ) -> ChartGenerationError | None: + columns = ( + config.get("columns") or config.get("all_columns") or config.get("groupby") + ) + if not columns: + return ChartGenerationError( + error_type="missing_columns", + message="Table chart missing required field: columns", + details=( + "Table charts require a 'columns' array to specify which " + "columns to display" + ), + suggestions=[ + "Add 'columns' field with array of column specifications", + "Example: 'columns': [{'name': 'product'}, {'name': 'sales', " + "'aggregate': 'SUM'}]", + "Each column can have optional 'aggregate' for metrics", + ], + error_code="MISSING_COLUMNS", + ) + + if not isinstance(columns, list): + return ChartGenerationError( + error_type="invalid_columns_format", + message="Columns must be a list", + details="The 'columns' field must be an array of column specifications", + suggestions=[ + "Ensure columns is an array: 'columns': [...]", + "Each column should be an object with 'name' field", + ], + error_code="INVALID_COLUMNS_FORMAT", + ) + + return None + + def extract_column_refs(self, config: Any) -> list[ColumnRef]: + if not isinstance(config, TableChartConfig): + return [] + refs: list[ColumnRef] = list(config.columns) + if config.filters: + for f in config.filters: + refs.append(ColumnRef(name=f.column)) + return refs Review Comment: **Suggestion:** `sort_by` references are not included in extracted column refs, so typos or non-existent sort columns skip dataset validation and only fail later during query execution. Include `sort_by` columns in reference extraction (and normalize them) so bad sort keys are rejected early with a dataset validation error. [incomplete implementation] <details> <summary><b>Severity Level:</b> Critical 🚨</summary> ```mdx - ❌ Table charts can sort by non-existent dataset columns. - ⚠️ Dataset validation ignores invalid sort_by keys entirely. - ⚠️ Users see runtime query errors instead of early feedback. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Submit a table chart request via MCP (generate_chart or generate_explore_link) with `config.chart_type="table"`, `columns=[{"name": "product"}]`, and `sort_by=[{"column": "bad_sort", "ascending": False}]`, where `"bad_sort"` is not a real dataset column, using the `sort_by` field defined in `TableChartConfig` (`superset/mcp_service/chart/schemas.py:1560-15`). 2. Schema validation goes through `SchemaValidator._pre_validate_chart_type` (`validation/schema_validator.py:146-196`) into `TableChartPlugin.pre_validate` (`superset/mcp_service/chart/plugins/table.py:46-82`); this only ensures that `columns` exists and is a list and does not inspect the `sort_by` contents. 3. Dataset validation in `ValidationPipeline._validate_dataset` (`validation/pipeline.py:99-110`) calls `DatasetValidator.validate_against_dataset` (`dataset_validator.py:98-154); `_extract_column_references` (`dataset_validator.py:8-33`) relies on `TableChartPlugin.extract_column_refs` (`plugins/table.py:84-91`), which returns `config.columns` plus filter ColumnRefs but omits any references derived from `config.sort_by`, so `"bad_sort"` is never checked against the dataset schema. 4. Column name normalization in `ValidationPipeline._normalize_column_names` (`validation/pipeline.py:150-187`) calls `TableChartPlugin.normalize_column_refs` (`plugins/table.py:106-118`), which normalizes `columns` and `filters` using `DatasetValidator.get_canonical_column_name` / `get_canonical_metric_name` but does not touch `sort_by`, leaving any sort column names unvalidated and unnormalized. 5. `map_table_config` constructs Superset form_data in `superset/mcp_service/chart/chart_utils.py:430-102`; after mapping columns and metrics, it translates `config.sort_by` into `form_data["order_by_cols"]` (lines 89-97), inserting `"bad_sort"` into the sort specification while Tier-1 `validate_and_compile` in `superset/mcp_service/chart/compile.py:16-76` validates only the column refs from the typed config and returns success. 6. When the generated chart or explore URL is later used to run the query (via Superset’s `ChartDataCommand` in `_compile_chart` or the Explore UI), the backend issues an ORDER BY on `"bad_sort"`, which does not exist as a dataset column, causing a database or query error at runtime instead of a structured dataset validation error that the MCP tools could surface earlier. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=549bcb3f72a5409294639b9112f5ca73&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=549bcb3f72a5409294639b9112f5ca73&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/mcp_service/chart/plugins/table.py **Line:** 84:91 **Comment:** *Incomplete Implementation: `sort_by` references are not included in extracted column refs, so typos or non-existent sort columns skip dataset validation and only fail later during query execution. Include `sort_by` columns in reference extraction (and normalize them) so bad sort keys are rejected early with a dataset validation error. 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%2F39922&comment_hash=867af202269617a3ca9cb80c1cafd6c34ba4571bea7aab7b0c2b23309400fe6e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39922&comment_hash=867af202269617a3ca9cb80c1cafd6c34ba4571bea7aab7b0c2b23309400fe6e&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]
