codeant-ai-for-open-source[bot] commented on code in PR #39922: URL: https://github.com/apache/superset/pull/39922#discussion_r3482306606
########## superset/mcp_service/chart/plugins/table.py: ########## @@ -0,0 +1,135 @@ +# 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 typing import Any + +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 = { + "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 + + def to_form_data( + self, config: Any, dataset_id: int | str | None = None + ) -> dict[str, Any]: + return map_table_config(config) + + def generate_name(self, config: Any, dataset_name: str | None = None) -> str: + what = _table_chart_what(config, dataset_name) + context = _summarize_filters(config.filters) + return self._with_context(what, context) + + def resolve_viz_type(self, config: Any) -> str: + return getattr(config, "viz_type", "table") + + def normalize_column_refs(self, config: Any, dataset_context: Any) -> Any: + config_dict = config.model_dump() + get_canonical = DatasetValidator._get_canonical_column_name + get_canonical_metric = DatasetValidator._get_canonical_metric_name + + for col in config_dict.get("columns") or []: + if col.get("saved_metric"): + col["name"] = get_canonical_metric(col["name"], dataset_context) + else: + col["name"] = get_canonical(col["name"], dataset_context) Review Comment: **Suggestion:** SQL-expression metrics in table columns have `name=None`, but this normalization path always canonicalizes `col["name"]` unless `saved_metric` is true. That sends `None` into `_get_canonical_column_name`, which raises and aborts the whole normalization pass. Add a guard to skip entries with `sql_expression` (same pattern used in the other plugins) so SQL metrics don't break normalization of the request. [null pointer] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ MCP generate_chart skips column case normalization for table configs. - ⚠️ SQL-expression metrics in table columns trigger normalization errors. - ⚠️ MCP generate_explore_link falls back to unnormalized configs for tables. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Call the MCP `generate_chart` tool defined in `superset/mcp_service/chart/tool/generate_chart.py` (see async `generate_chart` at lines 89–100) with a `GenerateChartRequest` whose `config` is a table chart using a SQL-expression metric in `columns`, e.g. reuse the documented sample in `superset/mcp_service/chart/tool/get_chart_type_schema.py:60–79`: `{"chart_type": "table", "columns": [{"name": "customer_name"}, {"name": "revenue", "aggregate": "SUM"}, {"sql_expression": "SUM(revenue) / COUNT(*)", "label": "Avg per Order"}]}`. 2. The request flows into `ValidationPipeline.validate_request_with_warnings()` in `superset/mcp_service/chart/validation/pipeline.py:63–71`, which after schema and dataset validation calls `_normalize_column_names()` at `pipeline.py:110–121` to normalize column names for the typed `TableChartConfig`. 3. `_normalize_column_names()` calls `DatasetValidator.normalize_column_names()`, which looks up the `TableChartPlugin` via the registry and invokes `TableChartPlugin.normalize_column_refs(config, dataset_context)` in `superset/mcp_service/chart/plugins/table.py:105–117`; inside this method `config.model_dump()` produces a `columns` entry for the SQL metric with `{"sql_expression": "...", "label": "Avg per Order", "name": None}` due to the `ColumnRef` rules in `schemas.py:11–52`. 4. The loop at `table.py:110–114` runs for each column; for the SQL metric entry `col.get("saved_metric")` is false, so it executes `col["name"] = get_canonical(col["name"], dataset_context)` with `col["name"] is None`, which calls `DatasetValidator._get_canonical_column_name(column_name, dataset_context)` in `superset/mcp_service/chart/validation/dataset_validator.py:312–324`; inside `_get_canonical_column_name`, `column_name.lower()` is evaluated on `None` and raises `AttributeError`, causing `DatasetValidator.normalize_column_names()` to fail and `ValidationPipeline._normalize_column_names()` to hit its `except (ImportError, AttributeError, KeyError, ValueError, TypeError)` block at `pipeline.py:69–73`, log "Column name normalization failed", and return the original request with all table columns (including non-SQL ones) left unnormalized. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=96332bf6cd214ec4ad6af9f1bb6f7bf9&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=96332bf6cd214ec4ad6af9f1bb6f7bf9&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:** 110:114 **Comment:** *Null Pointer: SQL-expression metrics in table columns have `name=None`, but this normalization path always canonicalizes `col["name"]` unless `saved_metric` is true. That sends `None` into `_get_canonical_column_name`, which raises and aborts the whole normalization pass. Add a guard to skip entries with `sql_expression` (same pattern used in the other plugins) so SQL metrics don't break normalization of the request. 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=4d282f0aaaa82deedae8d0a88687898e8eecf7abd4d545c98da1af473256f732&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39922&comment_hash=4d282f0aaaa82deedae8d0a88687898e8eecf7abd4d545c98da1af473256f732&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]
