codeant-ai-for-open-source[bot] commented on code in PR #41860: URL: https://github.com/apache/superset/pull/41860#discussion_r3575581099
########## superset/mcp_service/chart/plugins/histogram.py: ########## @@ -0,0 +1,199 @@ +# 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. + +"""Histogram 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, + map_histogram_config, +) +from superset.mcp_service.chart.plugin import BaseChartPlugin +from superset.mcp_service.chart.schemas import ColumnRef, HistogramChartConfig +from superset.mcp_service.chart.validation.dataset_validator import DatasetValidator +from superset.mcp_service.common.error_schemas import ChartGenerationError + + +class HistogramChartPlugin(BaseChartPlugin): + """Plugin for histogram chart type.""" + + chart_type = "histogram" + display_name = "Histogram" + native_viz_types: ClassVar[Mapping[str, str]] = { + "histogram_v2": "Histogram", + } + + def pre_validate( + self, + config: dict[str, Any], + ) -> ChartGenerationError | None: + if "column" not in config: + return ChartGenerationError( + error_type="missing_histogram_fields", + message="Histogram missing required field: 'column'", + details=( + "Histograms bin the values of a single numeric column " + "into frequency buckets" + ), + suggestions=[ + "Add 'column' field: {'name': 'numeric_column'}", + "Example: {'chart_type': 'histogram', " + "'column': {'name': 'trip_duration'}, 'bins': 10}", + ], + error_code="MISSING_HISTOGRAM_FIELDS", + ) + return None + + def extract_column_refs(self, config: Any) -> list[ColumnRef]: + if not isinstance(config, HistogramChartConfig): + return [] + refs: list[ColumnRef] = [config.column] + refs.extend(config.groupby or []) + 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_histogram_config(config) + + def generate_name(self, config: Any, dataset_name: str | None = None) -> str: + what = f"Distribution of {config.column.label or config.column.name}" + if config.groupby: + what += " by " + ", ".join(g.label or g.name for g in config.groupby) + context = _summarize_filters(config.filters) + return self._with_context(what, context) + + def post_map_validate( + self, + config: Any, + form_data: dict[str, Any], + dataset_id: int | str | None = None, + ) -> ChartGenerationError | None: + """Require a numeric binned column, mirroring the Explore UI. + + The frontend control panel restricts the histogram column to + ``GenericDataType.Numeric``; without this check an LLM picking a + text column passes pre-validation and only fails at query time. + """ + if not isinstance(config, HistogramChartConfig) or dataset_id is None: + return None + + dataset_context = DatasetValidator._get_dataset_context(dataset_id) + if dataset_context is None: + return None + + col_info = next( + ( + col + for col in dataset_context.available_columns + if col["name"].lower() == (config.column.name or "").lower() + ), + None, + ) + if col_info is None: + # Column existence is validated separately; don't double-report. + return None + + def _is_numeric(col: dict[str, Any]) -> bool: + if col.get("is_numeric", False): + return True + # Backends report many spellings (BIGINT, SMALLINT, REAL, + # NUMBER, DOUBLE PRECISION); substring-match the common stems. + type_upper = str(col.get("type", "")).upper() + return any( + stem in type_upper + for stem in ( + "INT", + "FLOAT", + "DOUBLE", + "DECIMAL", + "NUMERIC", + "REAL", + "NUMBER", + ) + ) Review Comment: **Suggestion:** The numeric type fallback check is too broad: matching `"INT"` as a substring will incorrectly treat non-numeric types like `INTERVAL` (and other type names containing `INT`) as numeric, so invalid histogram columns can pass validation and fail later at query time. Tighten this check to exact numeric type families (or explicit tokenized matching) and exclude known non-numeric types. [incorrect condition logic] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Histogram tool accepts non-numeric bin columns silently. - ⚠️ Agents may build histograms on invalid column types. - ⚠️ Downstream queries can fail or produce meaningless bins. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Define a Superset dataset whose ORM column has type rendered as "INTERVAL" and is_numeric=False, so build_dataset_context_from_orm() in superset/mcp_service/chart/validation/dataset_validator.py:42-60 produces an available_columns entry {"name": "event_duration", "type": "INTERVAL", "is_numeric": False}. 2. From an MCP client, call the generate_chart tool in superset/mcp_service/chart/tool/generate_chart.py:98-120 with request.config.chart_type="histogram" and config.column={"name": "event_duration"} pointing at that INTERVAL column and a valid dataset_id. 3. The request passes ValidationPipeline.validate_request_with_warnings() in superset/mcp_service/chart/validation/pipeline.py:90-145, which builds a DatasetContext via ValidationPipeline._get_dataset_context() (pipeline.py:165-172) and DatasetValidator._get_dataset_context() (dataset_validator.py:249-259); column existence validation succeeds because "event_duration" is present. 4. When the chart is compiled, chart_utils.map_config_to_form_data() in superset/mcp_service/chart/chart_utils.py:368-56 looks up HistogramChartPlugin and calls HistogramChartPlugin.post_map_validate() in superset/mcp_service/chart/plugins/histogram.py:87-162; inside _is_numeric() at lines 118-135, col_info["is_numeric"] is False, type_upper becomes "INTERVAL", and the substring check finds "INT" in "INTERVAL", causing _is_numeric() to incorrectly return True so the non-numeric INTERVAL column is accepted as numeric and no ChartGenerationError is raised, allowing an invalid histogram bin column through validation and into query execution. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=4c068a98ce3b4a589b12e7f143d9c0de&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=4c068a98ce3b4a589b12e7f143d9c0de&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/histogram.py **Line:** 124:135 **Comment:** *Incorrect Condition Logic: The numeric type fallback check is too broad: matching `"INT"` as a substring will incorrectly treat non-numeric types like `INTERVAL` (and other type names containing `INT`) as numeric, so invalid histogram columns can pass validation and fail later at query time. Tighten this check to exact numeric type families (or explicit tokenized matching) and exclude known non-numeric types. 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%2F41860&comment_hash=d04f909518ae2d0566b49696cc2d469daa3f927dbfb2ef35f3647244f084d70f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41860&comment_hash=d04f909518ae2d0566b49696cc2d469daa3f927dbfb2ef35f3647244f084d70f&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]
