codeant-ai-for-open-source[bot] commented on code in PR #39922:
URL: https://github.com/apache/superset/pull/39922#discussion_r3493337405


##########
superset/mcp_service/chart/plugins/mixed_timeseries.py:
##########
@@ -0,0 +1,173 @@
+# 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.
+
+"""Mixed timeseries 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 (
+    _mixed_timeseries_what,
+    _summarize_filters,
+    map_mixed_timeseries_config,
+)
+from superset.mcp_service.chart.plugin import BaseChartPlugin
+from superset.mcp_service.chart.schemas import ColumnRef, 
MixedTimeseriesChartConfig
+from superset.mcp_service.chart.validation.dataset_validator import 
DatasetValidator
+from superset.mcp_service.common.error_schemas import ChartGenerationError
+
+
+class MixedTimeseriesChartPlugin(BaseChartPlugin):
+    """Plugin for mixed_timeseries chart type."""
+
+    chart_type = "mixed_timeseries"
+    display_name = "Mixed Timeseries"
+    native_viz_types: ClassVar[Mapping[str, str]] = {
+        "mixed_timeseries": "Mixed Timeseries Chart",
+    }
+
+    def pre_validate(
+        self,
+        config: dict[str, Any],
+    ) -> ChartGenerationError | None:
+        missing_fields = []
+
+        if "x" not in config and "x_axis" not in config:
+            missing_fields.append("'x' (X-axis temporal column)")
+        if not config.get("y") and not config.get("metrics"):
+            missing_fields.append("'y' (primary Y-axis metrics)")
+        if not config.get("y_secondary") and not config.get("metrics_b"):
+            missing_fields.append("'y_secondary' (secondary Y-axis metrics)")
+
+        if missing_fields:
+            return ChartGenerationError(
+                error_type="missing_mixed_timeseries_fields",
+                message=(
+                    f"Mixed timeseries chart missing required fields: "
+                    f"{', '.join(missing_fields)}"
+                ),
+                details=(
+                    "Mixed timeseries charts require an x-axis, primary 
metrics, "
+                    "and secondary metrics"
+                ),
+                suggestions=[
+                    "Add 'x' field: {'name': 'date_column'}",
+                    "Add 'y' field: [{'name': 'revenue', 'aggregate': 'SUM'}]",
+                    "Add 'y_secondary': [{'name': 'orders', 'aggregate': 
'COUNT'}]",
+                    "Optional: 'primary_kind' and 'secondary_kind' for chart 
types",
+                ],
+                error_code="MISSING_MIXED_TIMESERIES_FIELDS",
+            )
+
+        for field_name in ["y", "y_secondary"]:
+            if not isinstance(config.get(field_name, []), list):
+                return ChartGenerationError(
+                    error_type=f"invalid_{field_name}_format",
+                    message=f"'{field_name}' must be a list of metrics",
+                    details=(
+                        f"The '{field_name}' field must be an array of metric "
+                        "specifications"
+                    ),
+                    suggestions=[
+                        f"Wrap in array: '{field_name}': "
+                        "[{'name': 'col', 'aggregate': 'SUM'}]",
+                    ],
+                    error_code=f"INVALID_{field_name.upper()}_FORMAT",
+                )

Review Comment:
   **Suggestion:** The list-type validation only inspects `y`/`y_secondary` 
keys, but this plugin also accepts legacy aliases (`metrics`/`metrics_b`). If 
callers use aliases with wrong types, pre-validation misses them and the 
request falls through to a generic Pydantic error path instead of returning the 
intended structured validation error. Validate both canonical and alias keys 
consistently. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ generate_chart returns generic error for alias metric misuse.
   - ⚠️ Mixed_timeseries callers get inconsistent validation feedback.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Call MCP tool `generate_chart` for a mixed timeseries chart with a config 
that uses
   alias metric keys but with the wrong type, for example `{"chart_type": 
"mixed_timeseries",
   "x": {"name": "order_date"}, "metrics": {"name": "revenue", "aggregate": 
"SUM"},
   "metrics_b": [{"name": "orders", "aggregate": "COUNT"}]}` (tool entry point 
in
   `superset/mcp_service/chart/tool/generate_chart.py:225-279`).
   
   2. The request flows into 
`ValidationPipeline.validate_request_with_warnings()`
   (`validation/pipeline.py:90-103`), which calls 
`SchemaValidator.validate_request()`
   (`validation/schema_validator.py:40-52`) and then 
`_pre_validate_chart_type()`
   (`schema_validator.py:146-196`).
   
   3. `_pre_validate_chart_type()` retrieves `MixedTimeseriesChartPlugin` and 
calls its
   `pre_validate()` (`plugins/mixed_timeseries.py:45-56, 78-92). The 
required-field checks at
   lines 53-56 correctly treat `"metrics"` / `"metrics_b"` as satisfying the 
presence of
   primary and secondary metrics, but the list-type validation loop at lines 
78-92 only
   inspects `"y"` and `"y_secondary"`. Because the config uses `"metrics"` and 
`"metrics_b"`
   and omits `"y"` / `"y_secondary"`, `config.get("y", [])` and 
`config.get("y_secondary",
   [])` both default to empty lists, so no `ChartGenerationError` is raised 
even though
   `"metrics"` is a dict, not a list.
   
   4. Pydantic then parses `GenerateChartRequest` and 
`MixedTimeseriesChartConfig`
   (`schemas.py:57-80, 1180-1259). The `y` field is declared as 
`List[ColumnRef]` with
   `validation_alias=AliasChoices("y", "metrics")` (`schemas.py:71-77), so the 
dict at
   `"metrics"` causes a structural validation error (invalid list type). This 
error is
   converted by `_enhance_validation_error()` (`schema_validator.py:201-239`) 
into a generic
   `"validation_error"` response instead of the intended, structured 
`"invalid_y_format"` /
   `"invalid_y_secondary_format"` errors, demonstrating that alias metric 
fields currently
   bypass the plugin’s explicit list-type validation.
   ```
   </details>
   
   [![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=49847f9a0dc74170af266c266356ef8b&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=49847f9a0dc74170af266c266356ef8b&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/mixed_timeseries.py
   **Line:** 78:92
   **Comment:**
        *Logic Error: The list-type validation only inspects `y`/`y_secondary` 
keys, but this plugin also accepts legacy aliases (`metrics`/`metrics_b`). If 
callers use aliases with wrong types, pre-validation misses them and the 
request falls through to a generic Pydantic error path instead of returning the 
intended structured validation error. Validate both canonical and alias keys 
consistently.
   
   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=639d3f175abfaf49c448ced997740b9fcced6f64a77c7ee2f15e8fed2f0488bd&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39922&comment_hash=639d3f175abfaf49c448ced997740b9fcced6f64a77c7ee2f15e8fed2f0488bd&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]

Reply via email to