You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "aminghadersohi (via GitHub)" <gi...@apache.org> on 2026/02/03 15:23:46 UTC

[PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

aminghadersohi opened a new pull request, #37639:
URL: https://github.com/apache/superset/pull/37639

   ### SUMMARY
   
   When generating chart previews and data for XY charts with a `group_by` dimension via the MCP service, the query context only included `groupby` columns but omitted the `x_axis` column. This caused series charts to lose their x-axis dimension entirely.
   
   For example, when creating a bar chart with `territory` as x-axis, `year` as group_by, and `SUM(sales)` as metric, the resulting query would be:
   ```sql
   SELECT year, SUM(sales) FROM ... GROUP BY year
   ```
   Instead of the correct:
   ```sql
   SELECT territory, year, SUM(sales) FROM ... GROUP BY territory, year
   ```
   
   The bug existed in 4 locations where query contexts are built:
   - `TablePreviewStrategy` in `get_chart_preview.py`
   - `VegaLitePreviewStrategy` in `get_chart_preview.py`
   - Fallback query context in `get_chart_data.py`
   - `generate_preview_from_form_data` in `preview_utils.py`
   
   The fix follows the pattern already used by `ASCIIPreviewStrategy`, which correctly included both `x_axis` and `groupby` columns in the query context's `columns` list.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   
   **Before:** Chart preview/data only shows groupby column + metrics (x_axis column missing)
   ```
   genre        | SUM(global_sales)
   -------------+------------------
   Platform     | 178.66
   Action       | 76.37
   ...
   ```
   
   **After:** Chart preview/data correctly shows x_axis + groupby + metrics
   ```
   platform | genre        | SUM(global_sales)
   ---------+--------------+------------------
   PS2      | Platform     | 72.51
   GC       | Platform     | 28.66
   ...
   ```
   
   ### TESTING INSTRUCTIONS
   
   1. Start Superset with MCP service enabled
   2. Use an MCP client to generate a bar chart with:
      - x-axis: any categorical column (e.g., `platform`)
      - group_by: another categorical column (e.g., `genre`)
      - metric: any aggregated metric (e.g., `SUM(global_sales)`)
   3. Verify the chart preview (table, vega_lite formats) includes all three columns
   4. Verify `get_chart_data` returns data with the x-axis column present
   5. Run tests: `pytest tests/unit_tests/mcp_service/chart/ -v`
   
   ### ADDITIONAL INFORMATION
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [ ] Introduces new feature or API
   - [ ] Removes existing feature or API


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2760067517


##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -64,12 +64,27 @@ def generate_preview_from_form_data(
         # Create query context from form data using factory
         from superset.common.query_context_factory import QueryContextFactory
 
+        # Build columns list: include x_axis and groupby for XY charts,
+        # fall back to form_data "columns" for table charts
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])

Review Comment:
   Good catch — fixed in 8fde07c. Now using `"columns" in form_data` instead of truthiness check.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37639:
URL: https://github.com/apache/superset/pull/37639#issuecomment-3842481400

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2760179157


##########
superset/mcp_service/chart/schemas.py:
##########
@@ -692,7 +696,11 @@ class XYChartConfig(BaseModel):
         False,
         description="Stack bars/areas on top of each other instead of side-by-side",
     )
-    group_by: ColumnRef | None = Field(None, description="Column to group by")
+    group_by: ColumnRef | None = Field(
+        None,
+        description="Column to group by (creates series/breakdown). "
+        "Use this field for series grouping — do NOT use 'series'.",

Review Comment:
   Good to know, thanks for the heads up. We can revisit this when we add support for those viz types — at that point we'd likely need separate config schemas for bubble/word cloud anyway since they have different field requirements.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2761890858


##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -36,6 +36,23 @@
 logger = logging.getLogger(__name__)
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])
+    raw_columns: list[str] = form_data.get("columns", [])

Review Comment:
   **Suggestion:** If `form_data["columns"]` exists but is `None` (or another non-list type), assigning it directly to `raw_columns` and then calling `.copy()` will raise an `AttributeError`, breaking previews for such requests instead of safely falling back to an empty list. [possible bug]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Preview generation errors when "columns" key is null
   - ⚠️ Table and XY previews may be blocked intermittently
   ```
   </details>
   
   ```suggestion
       raw_columns = form_data.get("columns") or []
       if not isinstance(raw_columns, list):
           raw_columns = []
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Invoke generate_preview_from_form_data(form_data, dataset_id, preview_format) in
   superset/mcp_service/chart/preview_utils.py (caller uses _build_query_columns at line 86).
   
   2. Provide form_data that contains the "columns" key with a null or non-list value, e.g.
   form_data = {"viz_type": "table", "columns": None}. The presence of the key is important.
   
   3. Inside _build_query_columns (lines 39-53), line 43 sets raw_columns =
   form_data.get("columns", []) which yields None. Because "columns" key exists, the later
   expression at line 45 uses raw_columns.copy() and attempts to call .copy() on None.
   
   4. This causes AttributeError: 'NoneType' object has no attribute 'copy', failing preview
   creation along the same path as ChartDataCommand execution. This reproduces whenever a
   request includes "columns": null.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/preview_utils.py
   **Line:** 43:43
   **Comment:**
   	*Possible Bug: If `form_data["columns"]` exists but is `None` (or another non-list type), assigning it directly to `raw_columns` and then calling `.copy()` will raise an `AttributeError`, breaking previews for such requests instead of safely falling back to an empty list.
   
   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.
   ```
   </details>



##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -36,6 +36,23 @@
 logger = logging.getLogger(__name__)
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])
+    raw_columns: list[str] = form_data.get("columns", [])
+
+    columns = raw_columns.copy() if "columns" in form_data else groupby_columns.copy()
+    if x_axis_config and isinstance(x_axis_config, str):
+        if x_axis_config not in columns:
+            columns.insert(0, x_axis_config)
+    elif x_axis_config and isinstance(x_axis_config, dict):
+        col_name = x_axis_config.get("column_name")
+        if col_name and col_name not in columns:
+            columns.insert(0, col_name)

Review Comment:
   **Suggestion:** When the x-axis is configured as an ad-hoc column (a dict without `column_name` but with `sqlExpression`), the current logic ignores it entirely, so the generated query columns omit the x-axis dimension and the preview query may not match the chart configuration; adding a fallback to include the dict itself when `column_name` is missing fixes this. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ x_axis omitted from preview query for ad-hoc expressions
   - ⚠️ Vega-Lite/table previews mismatch when using SQL expressions
   ```
   </details>
   
   ```suggestion
           if col_name:
               if col_name not in columns:
                   columns.insert(0, col_name)
           elif "sqlExpression" in x_axis_config and x_axis_config not in columns:
               columns.insert(0, x_axis_config)
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Call generate_preview_from_form_data(form_data, dataset_id, preview_format) in
   superset/mcp_service/chart/preview_utils.py (the call to _build_query_columns is at line
   86).
   
   2. Provide form_data where x_axis is an ad-hoc column dict without "column_name" but with
   a SQL expression, e.g. form_data["x_axis"] = {"sqlExpression": "YEAR(date)"} (this format
   is used by ad-hoc columns).
   
   3. _build_query_columns (lines 39-53) hits the dict branch at line 49, extracts col_name
   (line 50) which is None, and because no fallback exists the ad-hoc dict is ignored. The
   resulting columns list does not include the x_axis expression.
   
   4. The QueryContext created from these columns therefore omits the x-axis expression from
   SELECT and GROUP BY. The preview (via ChartDataCommand and subsequent preview generators)
   shows missing or incorrect x-axis, reproducing for ad-hoc x_axis usages.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/preview_utils.py
   **Line:** 51:52
   **Comment:**
   	*Logic Error: When the x-axis is configured as an ad-hoc column (a dict without `column_name` but with `sqlExpression`), the current logic ignores it entirely, so the generated query columns omit the x-axis dimension and the preview query may not match the chart configuration; adding a fallback to include the dict itself when `column_name` is missing fixes this.
   
   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.
   ```
   </details>



##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -36,6 +36,23 @@
 logger = logging.getLogger(__name__)
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])

Review Comment:
   **Suggestion:** When `form_data["groupby"]` is present but set to `None` (or any non-list value), assigning it directly to `groupby_columns` and then calling `.copy()` later will raise an `AttributeError`, causing preview generation to fail instead of gracefully treating it as no groupby columns. [possible bug]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ generate_preview_from_form_data preview fails (AttributeError)
   - ⚠️ LLM/form_data with null groupby triggers failure
   ```
   </details>
   
   ```suggestion
       groupby_columns = form_data.get("groupby") or []
       if not isinstance(groupby_columns, list):
           groupby_columns = []
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Call generate_preview_from_form_data(...) in
   superset/mcp_service/chart/preview_utils.py (the function defined at the top of the file;
   its usage of _build_query_columns is at line 86 in the PR hunk).
   
   2. Pass form_data containing "groupby": null (JSON null -> Python None). Example payload:
   form_data = {"viz_type": "echarts_timeseries_bar", "x_axis": "territory", "groupby":
   None}. The call site that triggers this is the line: columns =
   _build_query_columns(form_data) at line 86.
   
   3. Execution enters _build_query_columns (defined in the same file at lines 39-53). Line
   42 assigns groupby_columns = form_data.get("groupby", []) which returns None (because the
   key exists with null).
   
   4. Later, at line 45 (columns = raw_columns.copy() if "columns" in form_data else
   groupby_columns.copy()), Python attempts groupby_columns.copy() and raises AttributeError:
   'NoneType' object has no attribute 'copy'. The preview generation path blows up and
   returns a ChartError fallback. This reproduces deterministically when "groupby" is present
   and null.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/preview_utils.py
   **Line:** 42:42
   **Comment:**
   	*Possible Bug: When `form_data["groupby"]` is present but set to `None` (or any non-list value), assigning it directly to `groupby_columns` and then calling `.copy()` later will raise an `AttributeError`, causing preview generation to fail instead of gracefully treating it as no groupby columns.
   
   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.
   ```
   </details>



##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -56,6 +56,22 @@ class ChartLike(Protocol):
     uuid: Any
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])

Review Comment:
   **Suggestion:** `_build_query_columns` assumes that `form_data["groupby"]` is always a list, but if it is explicitly `None` or a scalar (e.g. a single string), calling `.copy()` will raise an AttributeError or produce an incorrect type, breaking table/vega previews for such charts. Normalizing the value to a list before copying avoids this runtime failure. [type error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Table preview generation may raise exceptions.
   - ❌ Vega-Lite preview queries can be aborted.
   - ⚠️ get_chart_preview tool returns ChartError instead.
   ```
   </details>
   
   ```suggestion
       groupby_columns = form_data.get("groupby") or []
   
       if not isinstance(groupby_columns, list):
           groupby_columns = [groupby_columns]
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Load a chart preview using get_chart_preview tool at
   superset/mcp_service/chart/tool/get_chart_preview.py: async
   _get_chart_preview_internal(...) which eventually instantiates PreviewFormatGenerator and
   calls a strategy (TablePreviewStrategy or VegaLitePreviewStrategy).
   
   2. The TablePreviewStrategy.generate path calls _build_query_columns(form_data) (callsite
   added at get_chart_preview.py:301 in the PR) passing form_data parsed from chart.params
   (from ChartDAO or transient chart).
   
   3. If the stored chart.params contains "groupby": null or "groupby": "year" (a scalar) — a
   realistic payload when form_data JSON comes from external LLMs or older saved exports —
   _build_query_columns executes groupby_columns: list[str] = form_data.get("groupby", [])
   then columns = groupby_columns.copy() at get_chart_preview.py:64.
   
   4. When groupby_columns is None, None.copy() raises AttributeError; when groupby_columns
   is a string, .copy() is a method error (strings don't have copy), causing the preview path
   to raise and the Table/Vega preview to fail. The failure appears in logs from
   get_chart_preview and results in ChartError returned to the caller.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/tool/get_chart_preview.py
   **Line:** 62:62
   **Comment:**
   	*Type Error: `_build_query_columns` assumes that `form_data["groupby"]` is always a list, but if it is explicitly `None` or a scalar (e.g. a single string), calling `.copy()` will raise an AttributeError or produce an incorrect type, breaking table/vega previews for such charts. Normalizing the value to a list before copying avoids this runtime failure.
   
   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.
   ```
   </details>



##########
superset/mcp_service/chart/tool/get_chart_data.py:
##########
@@ -178,6 +178,17 @@ async def get_chart_data(  # noqa: C901
                     metrics = form_data.get("metrics", [])
                     groupby_columns = form_data.get("groupby", [])
 
+                # Build query columns list: include both x_axis and groupby
+                x_axis_config = form_data.get("x_axis")
+                query_columns = groupby_columns.copy()

Review Comment:
   **Suggestion:** The code assumes that the `groupby` value from `form_data` is always a list and calls `.copy()` on it directly; if an existing chart was saved with `groupby` as `null` or a scalar (string), this will raise an `AttributeError` at runtime in the fallback path, preventing chart data retrieval. [type error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ get_chart_data MCP tool crashes on fallback charts.
   - ⚠️ Chart data previews fail for older unsaved charts.
   - ⚠️ Series/group_by chart previews may error inconsistently.
   ```
   </details>
   
   ```suggestion
                   if isinstance(groupby_columns, list):
                       query_columns = groupby_columns.copy()
                   elif groupby_columns:
                       # Handle older or malformed form_data where groupby is a scalar
                       query_columns = [groupby_columns]
                   else:
                       query_columns = []
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Create or find a chart record where chart.query_context is NULL and chart.params
   contains form_data with `"groupby": null` or `"groupby": "year"`. This falls into the
   fallback path in get_chart_data (file superset/mcp_service/chart/tool/get_chart_data.py).
   The fallback form_data is loaded at the line `form_data = utils_json.loads(chart.params)
   if chart.params else {}` (the fallback block around lines ~172-180).
   
   2. Invoke the MCP data tool for that chart by calling the get_chart_data tool function
   (superset/mcp_service/chart/tool/get_chart_data.py:def get_chart_data). Call it with
   request.identifier set to the chart's id so the code loads that chart (the ChartDAO lookup
   happens earlier in the same function).
   
   3. Execution reaches the fallback branch where groupby is read with `groupby_columns =
   form_data.get("groupby", [])` (line 179). If the saved form_data had `groupby: null` (->
   None) or `groupby: "year"` (-> str), groupby_columns becomes None or a string.
   
   4. The code then executes `query_columns = groupby_columns.copy()` (line 183). This raises
   an AttributeError ('NoneType' object has no attribute 'copy' or 'str' object has no
   attribute 'copy'), causing the get_chart_data invocation to fail and return an error from
   the inner except block that logs "Error retrieving chart data" and returns a ChartError.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/tool/get_chart_data.py
   **Line:** 183:183
   **Comment:**
   	*Type Error: The code assumes that the `groupby` value from `form_data` is always a list and calls `.copy()` on it directly; if an existing chart was saved with `groupby` as `null` or a scalar (string), this will raise an `AttributeError` at runtime in the fallback path, preventing chart data retrieval.
   
   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.
   ```
   </details>



##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -56,6 +56,22 @@ class ChartLike(Protocol):
     uuid: Any
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])
+
+    columns = groupby_columns.copy()
+    if x_axis_config and isinstance(x_axis_config, str):
+        if x_axis_config not in columns:
+            columns.insert(0, x_axis_config)
+    elif x_axis_config and isinstance(x_axis_config, dict):
+        col_name = x_axis_config.get("column_name")
+        if col_name and col_name not in columns:
+            columns.insert(0, col_name)

Review Comment:
   **Suggestion:** When `x_axis` is provided as a dict (for example, an ad‑hoc or SQL expression column configuration), `_build_query_columns` currently extracts only `column_name` and drops the rest of the configuration; if `column_name` is missing this silently omits the x‑axis from the query, so previews for such charts won't include the intended x‑axis dimension. Using the entire dict as the column specification ensures ad‑hoc x‑axis definitions are preserved in the query. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Vega-Lite previews missing ad-hoc x-axis dimension.
   - ❌ Table previews omit intended x-axis column.
   - ⚠️ Preview SQL GROUP BY incorrect for ad-hoc x_axis.
   ```
   </details>
   
   ```suggestion
           if x_axis_config not in columns:
               columns.insert(0, x_axis_config)
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Create or have a chart whose form_data.x_axis is an ad-hoc or SQL expression dict (for
   example: {"sqlExpression": "DATE_TRUNC('year', date)", "label": "year"}) stored in
   chart.params (ChartDAO result used in VegaLitePreviewStrategy or transient chart creation
   in _get_chart_preview_internal).
   
   2. Call get_chart_preview (superset/mcp_service/chart/tool/get_chart_preview.py), which
   selects VegaLitePreviewStrategy.generate or TablePreviewStrategy.generate and calls
   columns = _build_query_columns(form_data) (callsites in get_chart_preview.py:204 and
   get_chart_preview.py:301 in the PR).
   
   3. Inside _build_query_columns (defined at get_chart_preview.py:59), the dict
   x_axis_config path looks only for "column_name" (get("column_name")) and if absent does
   not add any column; the ad-hoc dict therefore is silently omitted from the columns list.
   
   4. QueryContextFactory.create (superset/common/query_context_factory.py:create at ~line
   39) receives a queries[0]["columns"] lacking the x_axis dict, so the generated SQL and
   GROUP BY omit the intended x-axis expression, producing incorrect preview results (missing
   dimension in SELECT/GROUP BY) visible in Table/Vega previews.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/tool/get_chart_preview.py
   **Line:** 69:71
   **Comment:**
   	*Logic Error: When `x_axis` is provided as a dict (for example, an ad‑hoc or SQL expression column configuration), `_build_query_columns` currently extracts only `column_name` and drops the rest of the configuration; if `column_name` is missing this silently omits the x‑axis from the query, so previews for such charts won't include the intended x‑axis dimension. Using the entire dict as the column specification ensures ad‑hoc x‑axis definitions are preserved in the query.
   
   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.
   ```
   </details>



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2760177656


##########
tests/unit_tests/mcp_service/chart/test_preview_utils.py:
##########
@@ -0,0 +1,146 @@
+# 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.
+
+"""
+Tests for preview_utils query context column building.
+"""
+
+
+class TestPreviewUtilsColumnBuilding:
+    """Tests for x_axis + groupby column building in generate_preview_from_form_data.
+
+    The function must build the columns list from both x_axis and groupby for
+    XY charts, and fall back to form_data["columns"] for table charts.
+    """
+
+    def test_xy_chart_uses_x_axis_and_groupby(self):
+        """Test XY chart form_data builds columns from x_axis + groupby."""
+        form_data = {
+            "x_axis": "territory",
+            "groupby": ["year"],
+            "metrics": [{"label": "SUM(sales)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+        elif x_axis_config and isinstance(x_axis_config, dict):
+            col_name = x_axis_config.get("column_name")
+            if col_name and col_name not in columns:
+                columns.insert(0, col_name)
+
+        assert columns == ["territory", "year"]
+
+    def test_table_chart_uses_columns_field(self):
+        """Test table chart form_data uses 'columns' field directly."""
+        form_data = {
+            "columns": ["name", "region", "sales"],
+            "metrics": [],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+
+        assert columns == ["name", "region", "sales"]
+
+    def test_xy_chart_x_axis_dict_format(self):
+        """Test XY chart with x_axis as dict (column_name key)."""
+        form_data = {
+            "x_axis": {"column_name": "order_date"},
+            "groupby": ["product_type"],
+            "metrics": [{"label": "SUM(revenue)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+        elif x_axis_config and isinstance(x_axis_config, dict):
+            col_name = x_axis_config.get("column_name")
+            if col_name and col_name not in columns:
+                columns.insert(0, col_name)
+
+        assert columns == ["order_date", "product_type"]
+
+    def test_no_x_axis_no_columns_uses_groupby(self):
+        """Test fallback to groupby when no x_axis and no columns."""
+        form_data = {
+            "groupby": ["category"],
+            "metrics": [{"label": "COUNT(*)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+
+        assert columns == ["category"]
+
+    def test_empty_form_data_returns_empty_columns(self):
+        """Test empty form_data returns empty columns list."""
+        form_data: dict = {
+            "metrics": [{"label": "COUNT(*)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+
+        assert columns == []
+
+    def test_x_axis_not_duplicated_when_in_groupby(self):
+        """Test x_axis is not added if already present in groupby."""
+        form_data = {
+            "x_axis": "territory",
+            "groupby": ["territory", "year"],
+            "metrics": [{"label": "SUM(sales)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)

Review Comment:
   These are unit tests — some duplication is intentional for readability and independence of each test case.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "kgabryje (via GitHub)" <gi...@apache.org>.
kgabryje merged PR #37639:
URL: https://github.com/apache/superset/pull/37639


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "kgabryje (via GitHub)" <gi...@apache.org>.
kgabryje commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2759946937


##########
superset/mcp_service/chart/schemas.py:
##########
@@ -692,7 +696,11 @@ class XYChartConfig(BaseModel):
         False,
         description="Stack bars/areas on top of each other instead of side-by-side",
     )
-    group_by: ColumnRef | None = Field(None, description="Column to group by")
+    group_by: ColumnRef | None = Field(
+        None,
+        description="Column to group by (creates series/breakdown). "
+        "Use this field for series grouping — do NOT use 'series'.",

Review Comment:
   I think that's good enough for now since we support only a few chart types, but FYI in case we add support for more in the future - some viz plugins (e.g. bubble, word cloud) DO have a 'series' field in their form data



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2759657634


##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -185,6 +185,19 @@ def generate(self) -> TablePreview | ChartError:
                     error_type="InvalidChart",
                 )
 
+            # Build columns list: include both x_axis and groupby
+            x_axis_config = form_data.get("x_axis")
+            groupby_columns = form_data.get("groupby", [])
+
+            columns = groupby_columns.copy()
+            if x_axis_config and isinstance(x_axis_config, str):
+                if x_axis_config not in columns:
+                    columns.insert(0, x_axis_config)
+            elif x_axis_config and isinstance(x_axis_config, dict):
+                col_name = x_axis_config.get("column_name")
+                if col_name and col_name not in columns:
+                    columns.insert(0, col_name)

Review Comment:
   **Suggestion:** When the x-axis is configured as an ad-hoc/SQL expression (a dict without `column_name`), the table preview's `columns` list will omit the x-axis entirely because it only looks for `column_name` instead of using the full dict configuration, so those charts will still lose their x-axis in the preview. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Table preview missing x-axis for ad-hoc x_axis charts.
   - ⚠️ MCP table previews used by clients show incorrect columns.
   - ⚠️ ASCIIPreview unaffected (already includes dict handling).
   ```
   </details>
   
   ```suggestion
                   # Include dict-based x_axis configs (e.g., ad-hoc/SQL expressions) directly
                   if x_axis_config not in columns:
                       columns.insert(0, x_axis_config)
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Create a chart form_data where the x-axis is an ad-hoc/SQL expression represented as a
   dict WITHOUT a `column_name` key (e.g., x_axis = {"sqlExpression": "DATE_TRUNC('month',
   order_date)"}). Put that form_data into a saved chart or a transient form_data key.
   
   2. Call the MCP preview tool endpoint which runs get_chart_preview ->
   _get_chart_preview_internal at superset/mcp_service/chart/tool/get_chart_preview.py. The
   TablePreview path is exercised when request.format == "table", which uses
   TablePreviewStrategy.generate (function context around lines 173-201).
   
   3. Inside TablePreviewStrategy.generate, the code that builds the columns list checks the
   x_axis dict branch at lines 196-199
   (superset/mcp_service/chart/tool/get_chart_preview.py:196-199). Because the dict lacks
   "column_name", col_name is None and the code does not insert anything into `columns`.
   
   4. QueryContextFactory.create is then called with queries containing "columns": columns
   (see factory.create call around lines 201-214). ChartDataCommand.run
   (superset/commands/chart/data/get_data_command.py:34-73) executes the query payload built
   from this QueryContext; since the ad-hoc x_axis expression was not added to `columns`, the
   resulting query payload lacks the x-axis dimension and the returned table preview will be
   missing the x-axis column.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/tool/get_chart_preview.py
   **Line:** 197:199
   **Comment:**
   	*Logic Error: When the x-axis is configured as an ad-hoc/SQL expression (a dict without `column_name`), the table preview's `columns` list will omit the x-axis entirely because it only looks for `column_name` instead of using the full dict configuration, so those charts will still lose their x-axis in the preview.
   
   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.
   ```
   </details>



##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -64,12 +64,27 @@ def generate_preview_from_form_data(
         # Create query context from form data using factory
         from superset.common.query_context_factory import QueryContextFactory
 
+        # Build columns list: include x_axis and groupby for XY charts,
+        # fall back to form_data "columns" for table charts
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])

Review Comment:
   **Suggestion:** Calling `.copy()` on `groupby` or `columns` assumes they are always lists, but if form data ever provides a single string or other scalar (a pattern used elsewhere in Superset), this will raise an AttributeError at runtime; normalizing these values to lists before copying makes the code robust to both single and multiple values. [type error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ MCP preview generation crashes on scalar groupby inputs.
   - ⚠️ Bar/line chart previews unavailable for affected requests.
   - ⚠️ Affects generate_preview_from_form_data preview endpoint logic.
   ```
   </details>
   
   ```suggestion
           groupby_columns = form_data.get("groupby") or []
           if not isinstance(groupby_columns, list):
               groupby_columns = [groupby_columns]
           raw_columns = form_data.get("columns") or []
           if not isinstance(raw_columns, list):
               raw_columns = [raw_columns]
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Start Superset with the MCP service and invoke preview generation logic which calls
   generate_preview_from_form_data() defined in superset/mcp_service/chart/preview_utils.py
   (function block beginning at line ~54 in that file).
   
   2. Send form_data where "groupby" is provided as a single string (e.g., {"groupby":
   "year"}) and "columns" is omitted or empty. The code path at preview_utils.py:69-73
   executes.
   
   3. At preview_utils.py:73 the code executes groupby_columns.copy(), but groupby_columns is
   a str not a list, so Python raises AttributeError: 'str' object has no attribute 'copy'.
   
   4. The AttributeError bubbles out, causing preview generation to fail and ChartError
   fallback to be skipped; reproduce by calling the MCP preview flow (per PR testing
   instructions) with a single-string groupby value.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/preview_utils.py
   **Line:** 70:71
   **Comment:**
   	*Type Error: Calling `.copy()` on `groupby` or `columns` assumes they are always lists, but if form data ever provides a single string or other scalar (a pattern used elsewhere in Superset), this will raise an AttributeError at runtime; normalizing these values to lists before copying makes the code robust to both single and multiple values.
   
   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.
   ```
   </details>



##########
tests/unit_tests/mcp_service/chart/test_preview_utils.py:
##########
@@ -0,0 +1,146 @@
+# 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.
+
+"""
+Tests for preview_utils query context column building.
+"""
+
+
+class TestPreviewUtilsColumnBuilding:
+    """Tests for x_axis + groupby column building in generate_preview_from_form_data.
+
+    The function must build the columns list from both x_axis and groupby for
+    XY charts, and fall back to form_data["columns"] for table charts.
+    """
+
+    def test_xy_chart_uses_x_axis_and_groupby(self):
+        """Test XY chart form_data builds columns from x_axis + groupby."""
+        form_data = {
+            "x_axis": "territory",
+            "groupby": ["year"],
+            "metrics": [{"label": "SUM(sales)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+        elif x_axis_config and isinstance(x_axis_config, dict):
+            col_name = x_axis_config.get("column_name")
+            if col_name and col_name not in columns:
+                columns.insert(0, col_name)
+
+        assert columns == ["territory", "year"]
+
+    def test_table_chart_uses_columns_field(self):
+        """Test table chart form_data uses 'columns' field directly."""
+        form_data = {
+            "columns": ["name", "region", "sales"],
+            "metrics": [],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+
+        assert columns == ["name", "region", "sales"]
+
+    def test_xy_chart_x_axis_dict_format(self):
+        """Test XY chart with x_axis as dict (column_name key)."""
+        form_data = {
+            "x_axis": {"column_name": "order_date"},
+            "groupby": ["product_type"],
+            "metrics": [{"label": "SUM(revenue)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+        elif x_axis_config and isinstance(x_axis_config, dict):
+            col_name = x_axis_config.get("column_name")
+            if col_name and col_name not in columns:
+                columns.insert(0, col_name)
+
+        assert columns == ["order_date", "product_type"]
+
+    def test_no_x_axis_no_columns_uses_groupby(self):
+        """Test fallback to groupby when no x_axis and no columns."""
+        form_data = {
+            "groupby": ["category"],
+            "metrics": [{"label": "COUNT(*)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+
+        assert columns == ["category"]
+
+    def test_empty_form_data_returns_empty_columns(self):
+        """Test empty form_data returns empty columns list."""
+        form_data: dict = {
+            "metrics": [{"label": "COUNT(*)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+
+        assert columns == []
+
+    def test_x_axis_not_duplicated_when_in_groupby(self):
+        """Test x_axis is not added if already present in groupby."""
+        form_data = {
+            "x_axis": "territory",
+            "groupby": ["territory", "year"],
+            "metrics": [{"label": "SUM(sales)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)

Review Comment:
   **Suggestion:** The logic that builds the `columns` list from `form_data` is duplicated in every test method, which is a maintainability bug: if the column-building rules change, some tests can silently become inconsistent with others or with the production logic. Extracting this into a single helper method used by all tests removes the duplication and ensures there is exactly one place to update the behavior. [possible bug]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Tests duplication in tests/unit_tests/mcp_service/chart/test_preview_utils.py
   - ❌ CI may miss regressions in preview column logic
   - ⚠️ Developer friction updating column-building rules
   - ⚠️ Harder to ensure parity with production function
   ```
   </details>
   
   ```suggestion
       def _build_columns(self, form_data: dict) -> list:
           """Helper to build columns from form_data in a single place."""
           x_axis_config = form_data.get("x_axis")
           groupby_columns = form_data.get("groupby", [])
           raw_columns = form_data.get("columns", [])
   
           columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
           if x_axis_config and isinstance(x_axis_config, str):
               if x_axis_config not in columns:
                   columns.insert(0, x_axis_config)
           elif x_axis_config and isinstance(x_axis_config, dict):
               col_name = x_axis_config.get("column_name")
               if col_name and col_name not in columns:
                   columns.insert(0, col_name)
           return columns
   
       def test_xy_chart_uses_x_axis_and_groupby(self):
           """Test XY chart form_data builds columns from x_axis + groupby."""
           form_data = {
               "x_axis": "territory",
               "groupby": ["year"],
               "metrics": [{"label": "SUM(sales)"}],
           }
   
           columns = self._build_columns(form_data)
   
           assert columns == ["territory", "year"]
   
       def test_table_chart_uses_columns_field(self):
           """Test table chart form_data uses 'columns' field directly."""
           form_data = {
               "columns": ["name", "region", "sales"],
               "metrics": [],
           }
   
           columns = self._build_columns(form_data)
   
           assert columns == ["name", "region", "sales"]
   
       def test_xy_chart_x_axis_dict_format(self):
           """Test XY chart with x_axis as dict (column_name key)."""
           form_data = {
               "x_axis": {"column_name": "order_date"},
               "groupby": ["product_type"],
               "metrics": [{"label": "SUM(revenue)"}],
           }
   
           columns = self._build_columns(form_data)
   
           assert columns == ["order_date", "product_type"]
   
       def test_no_x_axis_no_columns_uses_groupby(self):
           """Test fallback to groupby when no x_axis and no columns."""
           form_data = {
               "groupby": ["category"],
               "metrics": [{"label": "COUNT(*)"}],
           }
   
           columns = self._build_columns(form_data)
   
           assert columns == ["category"]
   
       def test_empty_form_data_returns_empty_columns(self):
           """Test empty form_data returns empty columns list."""
           form_data: dict = {
               "metrics": [{"label": "COUNT(*)"}],
           }
   
           columns = self._build_columns(form_data)
   
           assert columns == []
   
       def test_x_axis_not_duplicated_when_in_groupby(self):
           """Test x_axis is not added if already present in groupby."""
           form_data = {
               "x_axis": "territory",
               "groupby": ["territory", "year"],
               "metrics": [{"label": "SUM(sales)"}],
           }
   
           columns = self._build_columns(form_data)
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Open the test file tests/unit_tests/mcp_service/chart/test_preview_utils.py and inspect
   lines 23-146 (the TestPreviewUtilsColumnBuilding class). You will see the columns-building
   logic duplicated in every test method (lines 38-145 contain repeated blocks that compute
   `columns` from form_data).
   
   2. Run the specific test class: pytest
   tests/unit_tests/mcp_service/chart/test_preview_utils.py::TestPreviewUtilsColumnBuilding.
   The tests exercise only the inline, duplicated logic inside this file and do not import or
   call the production helper.
   
   3. Now change the production implementation that builds the query-context columns — e.g.,
   edit src/mcp_service/chart/preview_utils.py (function generate_preview_from_form_data) to
   alter column-building behavior (add/remove x_axis handling). Because the unit tests in
   tests/unit_tests/mcp_service/chart/test_preview_utils.py reimplement the logic themselves,
   running pytest again will NOT detect the divergence between production code and tests.
   
   4. Observe CI or local test runs: tests in
   tests/unit_tests/mcp_service/chart/test_preview_utils.py still pass (they validate the
   duplicated logic, not the production function), demonstrating that duplicated test logic
   can silently allow regressions. Extracting the logic into a single helper used by tests
   would ensure tests validate the actual production behavior.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/mcp_service/chart/test_preview_utils.py
   **Line:** 30:144
   **Comment:**
   	*Possible Bug: The logic that builds the `columns` list from `form_data` is duplicated in every test method, which is a maintainability bug: if the column-building rules change, some tests can silently become inconsistent with others or with the production logic. Extracting this into a single helper method used by all tests removes the duplication and ensures there is exactly one place to update the behavior.
   
   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.
   ```
   </details>



##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -279,6 +292,19 @@ def generate(self) -> VegaLitePreview | ChartError:
                     utils_json.loads(self.chart.params) if self.chart.params else {}
                 )
 
+            # Build columns list: include both x_axis and groupby
+            x_axis_config = form_data.get("x_axis")
+            groupby_columns = form_data.get("groupby", [])
+
+            columns = groupby_columns.copy()
+            if x_axis_config and isinstance(x_axis_config, str):
+                if x_axis_config not in columns:
+                    columns.insert(0, x_axis_config)
+            elif x_axis_config and isinstance(x_axis_config, dict):
+                col_name = x_axis_config.get("column_name")
+                if col_name and col_name not in columns:
+                    columns.insert(0, col_name)

Review Comment:
   **Suggestion:** The Vega-Lite preview has the same issue for dict-based x-axis configs: if the x-axis is an ad-hoc/SQL expression without a `column_name`, it is never added to the `columns` list, so the resulting query data still lacks the x-axis dimension for those charts. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Vega-Lite preview missing x-axis for ad-hoc x_axis charts.
   - ⚠️ Interactive previews show incorrect or collapsed series.
   - ⚠️ Downstream visualization logic builds specs without x-axis.
   ```
   </details>
   
   ```suggestion
                   # Include dict-based x_axis configs (e.g., ad-hoc/SQL expressions) directly
                   if x_axis_config not in columns:
                       columns.insert(0, x_axis_config)
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Prepare chart form_data where x_axis is a dict ad-hoc expression without `column_name`
   (e.g., x_axis = {"sqlExpression": "EXTRACT(YEAR FROM created_at)"}).
   
   2. Request a Vega-Lite preview via MCP (get_chart_preview -> _get_chart_preview_internal).
   When the preview format is "vega_lite", VegaLitePreviewStrategy.generate is executed
   (context around lines 282-316).
   
   3. VegaLitePreviewStrategy.generate builds the `columns` list and reaches the dict branch
   at lines 303-306 (superset/mcp_service/chart/tool/get_chart_preview.py:303-306). Because
   there is no "column_name" key, col_name is falsy and the ad-hoc x_axis is not inserted
   into `columns`.
   
   4. QueryContextFactory.create is invoked with queries including those `columns`
   (factory.create call around lines 308-316). ChartDataCommand.run
   (superset/commands/chart/data/get_data_command.py:34-73) runs the query without the x-axis
   expression, so the Vega-Lite preview data lacks the x-axis field and the visualization
   spec generated from returned data is missing that dimension.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/tool/get_chart_preview.py
   **Line:** 304:306
   **Comment:**
   	*Logic Error: The Vega-Lite preview has the same issue for dict-based x-axis configs: if the x-axis is an ad-hoc/SQL expression without a `column_name`, it is never added to the `columns` list, so the resulting query data still lacks the x-axis dimension for those charts.
   
   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.
   ```
   </details>



##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -64,12 +64,27 @@ def generate_preview_from_form_data(
         # Create query context from form data using factory
         from superset.common.query_context_factory import QueryContextFactory
 
+        # Build columns list: include x_axis and groupby for XY charts,
+        # fall back to form_data "columns" for table charts
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+        elif x_axis_config and isinstance(x_axis_config, dict):
+            col_name = x_axis_config.get("column_name")

Review Comment:
   **Suggestion:** For dict-style x_axis configs (e.g., adhoc or expression-based x-axes), the code only reads `column_name`, so when the config instead uses `label` or `sqlExpression` (as is common for adhoc columns) the x-axis is silently omitted from the `columns` list and the query still misses the x-axis dimension. [possible bug]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Adhoc/expression x_axis omitted from MCP previews.
   - ⚠️ Vega-Lite and table previews lose x-axis dimension.
   - ⚠️ Affects generate_preview_from_form_data correctness.
   ```
   </details>
   
   ```suggestion
               col_name = (
                   x_axis_config.get("column_name")
                   or x_axis_config.get("label")
                   or x_axis_config.get("sqlExpression")
               )
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Create form_data where x_axis is an adhoc/expression dict, for example:
   
      {"x_axis": {"sqlExpression": "DATE_TRUNC('year', created_at)"} , "groupby": ["genre"],
      "columns": []}.
   
      Call generate_preview_from_form_data() in superset/mcp_service/chart/preview_utils.py
      (function around line 54).
   
   2. Execution reaches preview_utils.py:77-80. The code only reads
   x_axis_config.get("column_name") and ignores "sqlExpression" or "label".
   
   3. Because "column_name" is absent, col_name is None and no insertion into columns occurs,
   so the x-axis SQL expression isn't included in the query context.
   
   4. The generated query and preview (table/Vega-Lite) miss the x-axis dimension; this
   reproduces the original class of bugs the PR fixes when x_axis is provided as an adhoc
   expression.
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/preview_utils.py
   **Line:** 78:78
   **Comment:**
   	*Possible Bug: For dict-style x_axis configs (e.g., adhoc or expression-based x-axes), the code only reads `column_name`, so when the config instead uses `label` or `sqlExpression` (as is common for adhoc columns) the x-axis is silently omitted from the `columns` list and the query still misses the x-axis dimension.
   
   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.
   ```
   </details>



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37639:
URL: https://github.com/apache/superset/pull/37639#issuecomment-3841987381

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2759840096


##########
tests/unit_tests/mcp_service/chart/test_preview_utils.py:
##########
@@ -0,0 +1,146 @@
+# 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.
+
+"""
+Tests for preview_utils query context column building.
+"""
+
+
+class TestPreviewUtilsColumnBuilding:
+    """Tests for x_axis + groupby column building in generate_preview_from_form_data.
+
+    The function must build the columns list from both x_axis and groupby for
+    XY charts, and fall back to form_data["columns"] for table charts.
+    """
+
+    def test_xy_chart_uses_x_axis_and_groupby(self):
+        """Test XY chart form_data builds columns from x_axis + groupby."""
+        form_data = {
+            "x_axis": "territory",
+            "groupby": ["year"],
+            "metrics": [{"label": "SUM(sales)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+        elif x_axis_config and isinstance(x_axis_config, dict):
+            col_name = x_axis_config.get("column_name")
+            if col_name and col_name not in columns:
+                columns.insert(0, col_name)
+
+        assert columns == ["territory", "year"]
+
+    def test_table_chart_uses_columns_field(self):
+        """Test table chart form_data uses 'columns' field directly."""
+        form_data = {
+            "columns": ["name", "region", "sales"],
+            "metrics": [],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+
+        assert columns == ["name", "region", "sales"]
+
+    def test_xy_chart_x_axis_dict_format(self):
+        """Test XY chart with x_axis as dict (column_name key)."""
+        form_data = {
+            "x_axis": {"column_name": "order_date"},
+            "groupby": ["product_type"],
+            "metrics": [{"label": "SUM(revenue)"}],
+        }
+
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+        elif x_axis_config and isinstance(x_axis_config, dict):
+            col_name = x_axis_config.get("column_name")
+            if col_name and col_name not in columns:
+                columns.insert(0, col_name)

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Incorrect Column Logic in Tests</b></div>
   <div id="fix">
   
   The column building logic in the test methods incorrectly treats empty 'columns' lists the same as missing 'columns', which can lead to wrong column selection for table charts with empty columns. The logic should distinguish table charts (use 'columns' if present) from XY charts (use groupby + x_axis). This matches the function's docstring and prevents bugs like using groupby for table charts with empty columns. The implementation in preview_utils.py has the same issue and should be fixed similarly.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
           if "columns" in form_data:
               columns = raw_columns.copy()
           else:
               columns = groupby_columns.copy()
               if x_axis_config and isinstance(x_axis_config, str):
                   if x_axis_config not in columns:
                       columns.insert(0, x_axis_config)
               elif x_axis_config and isinstance(x_axis_config, dict):
                   col_name = x_axis_config.get("column_name")
                   if col_name and col_name not in columns:
                       columns.insert(0, col_name)
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #bc15b0</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #37639:
URL: https://github.com/apache/superset/pull/37639#issuecomment-3843511356

   resolved the bot comments that have been responded to... a little pre-commit and we'll be there!


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37639:
URL: https://github.com/apache/superset/pull/37639#issuecomment-3845057065

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37639:
URL: https://github.com/apache/superset/pull/37639#issuecomment-3855526297

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2760142536


##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -64,12 +64,27 @@ def generate_preview_from_form_data(
         # Create query context from form data using factory
         from superset.common.query_context_factory import QueryContextFactory
 
+        # Build columns list: include x_axis and groupby for XY charts,
+        # fall back to form_data "columns" for table charts
+        x_axis_config = form_data.get("x_axis")
+        groupby_columns = form_data.get("groupby", [])
+        raw_columns = form_data.get("columns", [])
+
+        columns = raw_columns.copy() if raw_columns else groupby_columns.copy()
+        if x_axis_config and isinstance(x_axis_config, str):
+            if x_axis_config not in columns:
+                columns.insert(0, x_axis_config)
+        elif x_axis_config and isinstance(x_axis_config, dict):
+            col_name = x_axis_config.get("column_name")

Review Comment:
   Not applicable here. In the MCP service, `x_axis` is always set as a string by `map_xy_config()`. The dict handling is a defensive fallback matching the existing `ASCIIPreviewStrategy` pattern. Adhoc/expression x-axes aren't part of the MCP chart generation flow.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2760151895


##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -279,6 +292,19 @@ def generate(self) -> VegaLitePreview | ChartError:
                     utils_json.loads(self.chart.params) if self.chart.params else {}
                 )
 
+            # Build columns list: include both x_axis and groupby
+            x_axis_config = form_data.get("x_axis")
+            groupby_columns = form_data.get("groupby", [])
+
+            columns = groupby_columns.copy()
+            if x_axis_config and isinstance(x_axis_config, str):
+                if x_axis_config not in columns:
+                    columns.insert(0, x_axis_config)
+            elif x_axis_config and isinstance(x_axis_config, dict):
+                col_name = x_axis_config.get("column_name")
+                if col_name and col_name not in columns:
+                    columns.insert(0, col_name)

Review Comment:
   Same as above — `x_axis` is always a string in MCP-generated charts. The dict fallback matches the existing `ASCIIPreviewStrategy` pattern.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2760144908


##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -185,6 +185,19 @@ def generate(self) -> TablePreview | ChartError:
                     error_type="InvalidChart",
                 )
 
+            # Build columns list: include both x_axis and groupby
+            x_axis_config = form_data.get("x_axis")
+            groupby_columns = form_data.get("groupby", [])
+
+            columns = groupby_columns.copy()
+            if x_axis_config and isinstance(x_axis_config, str):
+                if x_axis_config not in columns:
+                    columns.insert(0, x_axis_config)
+            elif x_axis_config and isinstance(x_axis_config, dict):
+                col_name = x_axis_config.get("column_name")
+                if col_name and col_name not in columns:
+                    columns.insert(0, col_name)

Review Comment:
   Same as above — `x_axis` is always a string in MCP-generated charts. The dict fallback matches the existing `ASCIIPreviewStrategy` pattern.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37639:
URL: https://github.com/apache/superset/pull/37639#discussion_r2770383086


##########
superset/mcp_service/chart/tool/get_chart_data.py:
##########
@@ -178,6 +178,17 @@ async def get_chart_data(  # noqa: C901
                     metrics = form_data.get("metrics", [])
                     groupby_columns = form_data.get("groupby", [])
 
+                # Build query columns list: include both x_axis and groupby
+                x_axis_config = form_data.get("x_axis")
+                query_columns = groupby_columns.copy()

Review Comment:
   Fixed in 53089aa — using `or []` pattern across all three locations.



##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -36,6 +36,23 @@
 logger = logging.getLogger(__name__)
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])
+    raw_columns: list[str] = form_data.get("columns", [])
+
+    columns = raw_columns.copy() if "columns" in form_data else groupby_columns.copy()
+    if x_axis_config and isinstance(x_axis_config, str):
+        if x_axis_config not in columns:
+            columns.insert(0, x_axis_config)
+    elif x_axis_config and isinstance(x_axis_config, dict):
+        col_name = x_axis_config.get("column_name")
+        if col_name and col_name not in columns:
+            columns.insert(0, col_name)

Review Comment:
   Not applicable — in the MCP service, `x_axis` is always set as a string by `map_xy_config()`. The dict handling is a defensive fallback matching the existing `ASCIIPreviewStrategy` pattern. Adhoc/expression x-axes aren't part of the MCP chart generation flow.



##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -36,6 +36,23 @@
 logger = logging.getLogger(__name__)
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])

Review Comment:
   Good catch — fixed in 53089aa. Using `or []` instead of `.get(key, [])` to handle explicit null values.



##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -56,6 +56,22 @@ class ChartLike(Protocol):
     uuid: Any
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])
+
+    columns = groupby_columns.copy()
+    if x_axis_config and isinstance(x_axis_config, str):
+        if x_axis_config not in columns:
+            columns.insert(0, x_axis_config)
+    elif x_axis_config and isinstance(x_axis_config, dict):
+        col_name = x_axis_config.get("column_name")
+        if col_name and col_name not in columns:
+            columns.insert(0, col_name)

Review Comment:
   Not applicable — `x_axis` is always a string in MCP-generated charts. The dict fallback matches the existing `ASCIIPreviewStrategy` pattern.



##########
superset/mcp_service/chart/preview_utils.py:
##########
@@ -36,6 +36,23 @@
 logger = logging.getLogger(__name__)
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])
+    raw_columns: list[str] = form_data.get("columns", [])

Review Comment:
   Fixed in 53089aa alongside the groupby null guard.



##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -56,6 +56,22 @@ class ChartLike(Protocol):
     uuid: Any
 
 
+def _build_query_columns(form_data: Dict[str, Any]) -> list[str]:
+    """Build query columns list from form_data, including both x_axis and groupby."""
+    x_axis_config = form_data.get("x_axis")
+    groupby_columns: list[str] = form_data.get("groupby", [])

Review Comment:
   Fixed in 53089aa — using `or []` pattern.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37639:
URL: https://github.com/apache/superset/pull/37639#issuecomment-3843082089

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #37639:
URL: https://github.com/apache/superset/pull/37639#issuecomment-3842040505

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/37639?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :white_check_mark: All modified and coverable lines are covered by tests.
   :white_check_mark: Project coverage is 43.51%. Comparing base ([`e9b4941`](https://app.codecov.io/gh/apache/superset/commit/e9b494163b99872d0163d3d2c5a66742ad44a964?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`0352eca`](https://app.codecov.io/gh/apache/superset/commit/0352eca4a5a794cff25203b1389d5659c5501d12?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 16 commits behind head on master.
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff             @@
   ##           master   #37639       +/-   ##
   ===========================================
   + Coverage        0   43.51%   +43.51%     
   ===========================================
     Files           0      644      +644     
     Lines           0    49432    +49432     
     Branches        0     5546     +5546     
   ===========================================
   + Hits            0    21508    +21508     
   - Misses          0    27625    +27625     
   - Partials        0      299      +299     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/37639/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [hive](https://app.codecov.io/gh/apache/superset/pull/37639/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.78% <ø> (?)` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/37639/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.80% <ø> (?)` | |
   | [python](https://app.codecov.io/gh/apache/superset/pull/37639/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `43.50% <ø> (?)` | |
   | [unit](https://app.codecov.io/gh/apache/superset/pull/37639/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `100.00% <ø> (?)` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/37639?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] fix(mcp): include x_axis column in query context for series charts with group_by [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #37639:
URL: https://github.com/apache/superset/pull/37639#issuecomment-3842008722

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | 0352eca4a5a794cff25203b1389d5659c5501d12 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/69821303f40b680008c33f4e |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-37639--superset-docs-preview.netlify.app](https://deploy-preview-37639--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTM3NjM5LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.Ye7q6hqrhIYfXx-3SXNcptCc2yho8fxDSwFvE9BiYS0)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-37639--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org