Skip to content

fix(mcp): add sort_by option to XYChartConfig (#42627) - #44464

Merged
aminghadersohi merged 34 commits into
apache:masterfrom
FrancescoCastaldi:fix/mcp-xy-chart-sort-by
Oct 10, 2026
Merged

aminghadersohi merged 34 commits into
apache:masterfrom
FrancescoCastaldi:fix/mcp-xy-chart-sort-by

Conversation

@FrancescoCastaldi

@FrancescoCastaldi FrancescoCastaldi commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

Fixes #42627.

MCP bar charts and other XY charts had no option to configure sorting; non-temporal charts were hardcoded to alphabetical ordering by category name (x_axis_sort_series_type = "name" and x_axis_sort_series_ascending = True).

This PR adds comprehensive sorting support via the sort_by field to XYChartConfig:

  • Schema & Validation:
    • Adds sort_by: SortByConfig | str | List[SortByConfig | str] | None to XYChartConfig with aliases (x_axis_sort, order_by, order_by_cols).
    • Supports bare strings, dicts, pair format [col, asc], and single-item lists (defaulting bare strings to descending order, and rejecting multi-column lists).
    • Adds saved_metric: bool | None to SortByConfig to track and preserve metric status across validation stages.
  • Form Data & Sorting Logic (add_xy_sort_config in chart_utils.py):
    • When non-temporal, sets x_axis_sort and x_axis_sort_asc, alongside backward-compatibility keys x_axis_sort_series_type ("name" if sorting by x-axis dimension, "value" otherwise) and x_axis_sort_series_ascending.
    • Supports case-insensitive matching for X-axis dimension name and label.
    • Supports adhoc SQL expression metrics (sql_expression / sqlExpression).
    • When temporal, ignores sort_by with a warning in form_data["_mcp_warnings"].
  • Plugin Column Extraction & Normalization (XYChartPlugin in xy.py):
    • Resolves saved metrics against dataset_context.available_metrics when not explicitly present in Y metrics, marking saved_metric=True.
    • Emits ColumnRef(name=sort_col, saved_metric=is_saved) so DatasetValidator._validate_columns_exist passes without rejecting independent saved metrics.
    • Excludes covered metrics and labels from redundant physical column references.
  • Query Compilation (_resolve_x_axis_sort_target in chart_helpers.py):
    • Resolves sort column targets against form_data["metrics"], matching by label, column name, or sqlExpression case-insensitively, and sets queries[0]["orderby"].

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A (Backend MCP API / Schema change)

TESTING INSTRUCTIONS

Run unit tests for MCP chart schemas, utils, helpers, and validation:

pytest tests/unit_tests/mcp_service/chart/test_chart_schemas.py \
       tests/unit_tests/mcp_service/chart/test_chart_utils.py \
       tests/unit_tests/mcp_service/chart/test_chart_helpers.py \
       tests/unit_tests/mcp_service/chart/validation/test_dataset_validator.py

All tests pass (1916 passed across MCP chart test suite), covering:

  • Schema coercion of strings, dicts, pairs, and aliases.
  • Rejection of invalid multi-column sort lists.
  • Case-insensitive X-axis sorting and SQL expression metrics.
  • Query dictionary orderby mapping.
  • Saved metrics validation when not present in Y.

ADDITIONAL INFORMATION

@bito-code-review

bito-code-review Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #7839c0

Actionable Suggestions - 0
Additional Suggestions - 2
  • superset/mcp_service/chart/plugins/xy.py - 2
    • sort_by resolves to label · Line 58-59
      `_resolve_name` returns `y_col["label"]` when `sort_by` matches a y metric's display label, but returns `y_col["name"]` for a name match and a canonical name via `get_canonical` otherwise. The label is a display string, not a canonical column/metric name, so the resolved `sort_by` key is inconsistent with the function's stated intent and may not match any dataset column/metric when a custom label is set. Return the canonical name in the label branch too.
    • unreachable sort branches · Line 135-143
      The list/str/dict branches of this nested ternary are unreachable: XYChartConfig.sort_by is coerced to a single SortByConfig by the `coerce_sort_by` field validator (schemas.py:2363-2384), and `extract_column_refs` early-returns unless config is an XYChartConfig. Only the `sort_entry.column` branch can execute. The 4-way nested ternary is also hard to read; collapse it to `sort_entry.column`.
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • superset/mcp_service/chart/chart_utils.py - 1
  • superset/mcp_service/chart/schemas.py - 2
Review Details
  • Files reviewed - 5 · Commit Range: ccf02c4..ccf02c4
    • superset/mcp_service/chart/chart_utils.py
    • superset/mcp_service/chart/plugins/xy.py
    • superset/mcp_service/chart/schemas.py
    • tests/unit_tests/mcp_service/chart/test_chart_schemas.py
    • tests/unit_tests/mcp_service/chart/test_chart_utils.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - 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 documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

@codecov

codecov Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.85106% with 36 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.54%. Comparing base (3bc9e9e) to head (d8a08f6).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
superset/mcp_service/chart/plugins/xy.py 66.66% 19 Missing and 11 partials ⚠️
superset/mcp_service/chart/chart_utils.py 88.23% 5 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #44464      +/-   ##
==========================================
- Coverage   82.79%   82.54%   -0.26%     
==========================================
  Files        3016     3006      -10     
  Lines      192511   191190    -1321     
  Branches    44840    44214     -626     
==========================================
- Hits       159399   157810    -1589     
- Misses      30079    30337     +258     
- Partials     3033     3043      +10     
Flag Coverage Δ
hive 35.34% <10.10%> (-0.05%) ⬇️
mysql 53.70% <10.10%> (-0.09%) ⬇️
postgres 53.71% <10.10%> (-0.09%) ⬇️
presto 37.12% <10.10%> (-0.06%) ⬇️
python 86.46% <80.85%> (+<0.01%) ⬆️
sqlite 53.45% <10.10%> (-0.09%) ⬇️
unit 80.08% <80.85%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment on lines +131 to +145
if config.sort_by:
sort_entry = config.sort_by
if isinstance(sort_entry, list) and sort_entry:
sort_entry = sort_entry[0]
sort_col = (
sort_entry.column
if isinstance(sort_entry, SortByConfig)
else sort_entry
if isinstance(sort_entry, str)
else sort_entry.get("column")
if isinstance(sort_entry, dict)
else None
)
if sort_col:
refs.append(ColumnRef(name=sort_col))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: sort_by is always added as a normal column reference, so saved metrics and Y-axis labels fail dataset validation before normalization can resolve them.

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes · 🏷️ Api mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/mcp_service/chart/plugins/xy.py
**Line:** 131:145
**Comment:**
	*Api Mismatch: `sort_by` is always added as a normal column reference, so saved metrics and Y-axis labels fail dataset validation before normalization can resolve them.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 91d10c4.

Added a guard that skips adding sort_by as a separate ColumnRef when its name is already covered by the x-axis, y-axis, or group-by fields, preventing metric labels from being validated as physical columns.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of fdb3ea5.

_normalize_xy_sort_by now passes sort_by through _update_sort_by_column, which resolves canonical names and saved-metric status before further processing.

If that's not right, unresolve this thread and CodeAnt will leave it open.

@FrancescoCastaldi FrancescoCastaldi Sep 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review and suggestions! This is now fully resolved and verified across the pipeline as of fdb3ea5:

  • extract_column_refs checks covered XY names (including x-axis, group-by, and y-axis metrics/labels and SQL expressions), skipping redundant ColumnRef additions that previously triggered premature validation failures.
  • Saved metrics and SQL expression metrics are resolved against dataset_context.available_metrics with saved_metric=True.
  • End-to-end integration tests were added in TestValidationPipelineWithXYChartSortBy to ensure sort_by traverses ValidationPipeline and sets form_data["x_axis_sort"], correctly resolving to metric labels (e.g. SUM(sales)).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 81af1e5.

sort_by is now normalized through _update_sort_by_column, which resolves canonical names and marks saved metrics before downstream validation.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 4f996ea.

sort_by entries are normalized through _update_sort_by_column, which resolves canonical names and preserves saved-metric status via SortByConfig before validation.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 916ffe2.

Added sort-by normalization that resolves saved metrics and Y-axis labels to canonical names before validation, preserving the saved-metric status in SortByConfig.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 81a94cc.

Added sort-by normalization that resolves saved metrics and Y-axis labels to canonical names before validation, preserving the saved-metric status in SortByConfig.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 251ef2c.

Added sort-by normalization that resolves saved metrics and Y-axis labels to canonical names before validation, preserving the saved-metric status in SortByConfig.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of ee9a0b4.

sort_by is now normalized through _update_sort_by_column, which resolves the canonical column or metric name and preserves saved-metric status before further processing.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Comment thread superset/mcp_service/chart/schemas.py Outdated
Comment on lines +2369 to +2376
if isinstance(v, str):
return SortByConfig(column=v, ascending=False)
if isinstance(v, list):
if not v:
return None
first = v[0]
if isinstance(first, str):
return SortByConfig(column=first, ascending=False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Multi-item lists are accepted by the annotated field but only the first entry is retained, silently dropping additional sort criteria from valid requests.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Api mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/mcp_service/chart/schemas.py
**Line:** 2369:2376
**Comment:**
	*Api Mismatch: Multi-item lists are accepted by the annotated field but only the first entry is retained, silently dropping additional sort criteria from valid requests.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 91d10c4.

The validator now rejects lists containing more than one sort specification with an explicit error instead of retaining only the first entry. The field description also states that multi-column sorting is unsupported for XY charts.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of ff3dc4e.

Multi-item sort lists are now rejected with a clear validation error instead of being reduced to the first entry. The field description also documents that XY charts support only a single sort column.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of fdb3ea5.

The sort_by validator now raises ValueError when a list contains more than one sort entry, preventing additional criteria from being silently discarded.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 81af1e5.

The validator now rejects lists with more than one sort entry by raising ValueError, preventing additional criteria from being silently discarded.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of a8ab8a7.

The validator now rejects lists with more than one sort entry by raising ValueError, preventing additional criteria from being silently discarded.

If that's not right, unresolve this thread and CodeAnt will leave it open.

@FrancescoCastaldi
FrancescoCastaldi force-pushed the fix/mcp-xy-chart-sort-by branch 2 times, most recently from b8aa3be to f396a3b Compare September 20, 2026 20:42
@bito-code-review

bito-code-review Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #9bbe55

Actionable Suggestions - 0
Additional Suggestions - 3
  • superset/mcp_service/chart/plugins/xy.py - 1
    • sort resolves to display label · Line 57-57
      In `_resolve_name`, when `sort_by` matches a y column's `label`, the code returns `y_col["label"]` (a display label), not the canonical column name. `normalize_column_refs` canonicalizes y `name` fields (lines 160-166) but not `label`, so a label differing from the column name yields an invalid sort column that `chart_utils._apply_xy_sort` writes into `form_data["x_axis_sort"]`. Return `y_col["name"]` instead.
  • tests/unit_tests/mcp_service/chart/test_chart_utils.py - 1
    • Weak test assertion · Line 2679-2680
      `test_extract_column_refs_includes_sort_by` asserts `"sales" in ref_names`, but `sales` is already in `y`, so the assertion passes even if the `sort_by` branch in `XYChartPlugin.extract_column_refs` is removed. Use a sort column not present in `x`/`y` (e.g. `profit`) and assert it, so the test actually guards the sort_by inclusion it claims to cover.
  • superset/mcp_service/chart/chart_utils.py - 1
    • redundant sort coercion · Line 1130-1138
      The `isinstance(sort_entry, list/str/dict)` branches duplicate `XYChartConfig.coerce_sort_by` (schemas.py:2363), which already converts str/dict/list to `SortByConfig` during pydantic validation. By the time `add_xy_sort_config` runs, `config.sort_by` is already `SortByConfig | None`, so these branches are unreachable dead code.
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • superset/mcp_service/chart/schemas.py - 1
  • superset/mcp_service/chart/chart_utils.py - 1
  • superset/mcp_service/chart/plugins/xy.py - 1
Review Details
  • Files reviewed - 5 · Commit Range: f396a3b..f396a3b
    • superset/mcp_service/chart/chart_utils.py
    • superset/mcp_service/chart/plugins/xy.py
    • superset/mcp_service/chart/schemas.py
    • tests/unit_tests/mcp_service/chart/test_chart_schemas.py
    • tests/unit_tests/mcp_service/chart/test_chart_utils.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - 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 documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

@gabotorresruiz gabotorresruiz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the work here Francesco, and for the very thorough issue that preceded it. I checked the branch out and ran it against a real dataset, and I think the mapping needs one more hop before the sort actually takes effect.

Blocking: x_axis_sort expects a metric label, not a column name

add_xy_sort_config writes the config value straight through at superset/mcp_service/chart/chart_utils.py:1149, but sortOperator only emits a sort when x_axis_sort is one of sortableLabels, which is the x-axis label plus getMetricLabel(...) of each metric (superset-frontend/packages/superset-ui-chart-controls/src/operators/sortOperator.ts:34-46). For y=[{name: "sales", aggregate: "SUM"}] the metric label is SUM(sales), so x_axis_sort: "sales" matches nothing and no sort post-processing is produced.

What I verified on this branch:

  • sortOperator with metrics: [SUM(amount)] and x_axis_sort: 'amount' returns undefined, for both x_axis_sort_asc values. The same call with x_axis_sort: 'SUM(amount)' returns {operation: 'sort', options: {by: 'SUM(amount)', ascending: false}}.
  • The spelling that would work is not reachable from the tool. ValidationPipeline.validate_request_with_warnings rejects sort_by: "SUM(amount)" with Column 'SUM(amount)' not found in dataset, rejects a custom metric label, and rejects a saved metric name with 'count' matches a saved metric but the ref doesn't have saved_metric=true. That happens because extract_column_refs adds the sort target as a plain ColumnRef (superset/mcp_service/chart/plugins/xy.py:129-143) and dataset validation runs before normalize_column_refs. The CodeAnt bot flagged the same root cause on xy.py, and it checks out.

So the only accepted input is a physical column name, and a physical column name is the one value the sort contract cannot use. sort_by: "<x-axis column>" does produce a sort because it takes the is_sort_index branch, but that is already the default ordering, so for the metric ranking the issue asks for, the new field currently does nothing.

This worked for me in add_xy_sort_config:

sort_target = sort_entry.column
for y_col in config.y or []:
    if (y_col.label or "").lower() == sort_target.lower() or (
        y_col.name or ""
    ).lower() == sort_target.lower():
        metric = create_metric_object(y_col)
        sort_target = metric if isinstance(metric, str) else metric["label"]
        break
form_data["x_axis_sort"] = sort_target

extract_column_refs also needs to stop emitting a ColumnRef for a sort target that already matches a y entry, otherwise the label and saved metric spellings keep failing validation before they ever reach _normalize_xy_sort_by.

On the tests: test_non_temporal_sort_by_metric_descending asserts form_data["x_axis_sort"] == "sales", which is exactly the value that makes the sort inert, so it pins the current behaviour rather than the intent. And test_normalize_column_refs_matches_y_metric_label passes only because it calls normalize_column_refs directly; the same config through ValidationPipeline is rejected. One test that drives sort_by through the pipeline and asserts x_axis_sort == "SUM(sales)" would cover both.

Not a blocker, but worth knowing

sort_by has no effect on what the MCP tools themselves return. _build_single_query_dict reads only form_data["orderby"] and sort_by_metric (superset/mcp_service/chart/chart_helpers.py:689-703), and the MCP path builds no post_processing, so get_chart_data, get_chart_sql and get_chart_preview emit no ORDER BY. Running it against a real SQLite dataset, sort_by="amount" ascending and descending both produced the identical statement and identical row order, the same as omitting sort_by entirely. This is pre-existing (TableChartConfig.sort_by has the same gap), so I would not hold the PR on it, but it means the sort only shows up once the chart is opened in Explore.

Happy to pair on any of this if it helps.

@aminghadersohi aminghadersohi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified at f396a3b: sort_by by saved metric or Y-axis label is rejected by dataset validation on every path, a 2-item list is silently truncated, and the new column-ref test still passes with the feature deleted. Graded both codeant threads and bito's three inline.

Comment thread superset/mcp_service/chart/schemas.py Resolved
@netlify

netlify Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 0f4150b
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ac8f6c6088aa40008364c3e
😎 Deploy Preview https://deploy-preview-44464--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

Francesco Castaldi added 2 commits September 29, 2026 11:04
db5e1b4 re-applied the literal suggestions from the 09-21 review round, but those threads were already superseded and resolved: it dropped the x/y/group_by covered-name dedup and the saved_metric flag on uncovered sort refs in extract_column_refs, rejected the [column, ascending] pair documented in the sort_by description, and introduced two E501 lines plus a ruff-format diff.

The tree is identical to 81a94cc again. Scoped mcp_service chart suite: 552 passed; ruff check and ruff format clean.
@FrancescoCastaldi

Copy link
Copy Markdown
Contributor Author

@rusackas db5e1b4 slipped in while re-checking the older review round and re-applied two suggestions from the 09-21 review whose threads were already superseded and resolved. It also rejected the [column, ascending] pair documented in the sort_by description, dropped the covered-name/saved_metric handling in extract_column_refs, and broke pre-commit (E501 + a ruff-format diff).

Reverted in 251ef2c, so the tree is identical to 81a94cc again. Scoped mcp_service suite: 552 passed, ruff clean. CI is rerunning on this head.

@bito-code-review

bito-code-review Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #73a434

Actionable Suggestions - 0
Additional Suggestions - 1
  • superset/mcp_service/chart/schemas.py - 1
    • Duplicated pair-form predicate · Line 2611-2612
      This inline pair check re-encodes the exact predicate already implemented in `_coerce_sort_item` (schemas.py:2491-2496): list/tuple, len 2, str + bool. Two copies of the pair grammar must now change in sync (e.g. if `[column, 'asc']` string directions are ever supported). Reordering the `len(v) > 1` guard first and delegating to `_coerce_sort_item` keeps a single definition.
Review Details
  • Files reviewed - 4 · Commit Range: 81a94cc..251ef2c
    • superset/mcp_service/chart/plugins/xy.py
    • superset/mcp_service/chart/schemas.py
    • tests/unit_tests/mcp_service/chart/test_chart_schemas.py
    • tests/unit_tests/mcp_service/chart/test_chart_utils.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - 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 documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

@rusackas

Copy link
Copy Markdown
Member

@aminghadersohi / @gabotorresruiz please take another spin and see how it looks now :D

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 30, 2026
@rusackas

rusackas commented Oct 2, 2026

Copy link
Copy Markdown
Member

Heya @FrancescoCastaldi, LGTM still stands on the content. Looks like a big MCP refactor merged to master today (#44746) and that's what's conflicting here now, not leftover review stuff. Want to rebase, or should I take a stab at it?

@FrancescoCastaldi

FrancescoCastaldi commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @rusackas! All set, rebased and merged with master against #44746.

Resolved the conflicts in chart_helpers.py and test_chart_helpers.py by aligning with the new public build_single_query_dict, ensuring full compliance with the plugin architectural contracts, and keeping both test suites intact. All 2,800+ chart MCP unit tests and ruff lint/format checks are passing green.

Ready for merge whenever you're good!

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Oct 2, 2026

@gabotorresruiz gabotorresruiz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for sticking with this one Francesco, and for working through all the bot threads. Re-reviewing at 9df716b: the sort is real now, so I am clearing my earlier request for changes.

I checked out the head, built a dataset over a real SQLite table and drove generate_chart through ValidationPipeline for 22 sort_by spellings, then rendered and executed each query. Sorting by a y column, a metric label, a custom label, a lowercase metric label, an adhoc SQL label, a saved metric that is in y, the x-axis column, the dict form, the pair form and the x_axis_sort alias each produce an ORDER BY and a different row order than the control run: Bananas, Cherries, Dates, Apples descending by SUM(amount), against Apples, Bananas, Cherries, Dates with no sort_by. I also ran every resulting x_axis_sort value through sortOperator in jest, and each one returns a real sort post-processing operation, while the old 'amount' spelling still returns undefined.

Four mutants, all killed: disabling add_xy_sort_config fails 22 tests, the extract_column_refs sort branch 6, the new build_single_query_dict branch 6, and _normalize_xy_sort_by 4. Copied onto the merge base, 23 of the new tests fail and two of the modules will not even import. tests/unit_tests/mcp_service/chart is 2807 passed, 3 skipped at the head. I also re-ran the cases from the older threads: a saved series-sort value such as sum or max sitting in x_axis_sort produces no orderby and no error, and a multi-item sort_by now raises instead of silently collapsing to the first entry.

CI is fully green. Everything below is non-blocking.

)

if dataset_context and getattr(dataset_context, "available_metrics", None):
for m in dataset_context.available_metrics:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a blocker, but I do not think this branch can reach a working sort.

Probing generate_chart against a dataset whose saved metric total_sales is not in y: sort_by: "total_sales" is rejected at dataset validation with saved_metric_not_marked, because extract_column_refs reads the flag off the incoming config (saved_metric is still None there) while _normalize_xy_sort_by only sets it in the normalization layer, which runs after validation. Taking the error's advice and sending sort_by: {"column": "total_sales", "saved_metric": true} does pass validation, and then add_xy_sort_config drops it with sort_by='total_sales' was ignored: XY charts can only sort by the x-axis or a y-axis metric. So both spellings end with no sort, and the error message points at the one that warns.

The contract itself looks right to me, since sortOperator can only sort by the x-axis label or a label that is in the query's metrics. But that means this available_metrics lookup and the saved_metric=True ref it produces only ever buy a warning. Would it be simpler to drop them and have the validator say the target must be the x column or a y metric? Or is there a path where an independent saved metric does sort that I am missing?

Comment thread superset/mcp_service/chart/schemas.py Outdated
ge=1,
le=10000,
)
sort_by: SortByConfig | str | List[SortByConfig | str] | None = Field(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a small NIT on the annotation: the description promises [column, ascending] and coerce_sort_by handles it two lines below, but the list member serializes as items: {anyOf: [string, SortByConfig]}, so the pair form is not valid against the schema the tool advertises. I ran XYChartConfig.model_json_schema() through Draft202012Validator: ["amount", true] fails the schema while pydantic accepts it, so a client that validates against inputSchema cannot send the form the description recommends.

A Tuple[str, bool] member in the union would line the two up, and max_length=1 on the list member would put the single-sort-column rule in the schema too.

if not matched_label:
form_data.setdefault("_mcp_warnings", []).append(
f"sort_by='{sort_entry.column}' was ignored: XY charts can "
"only sort by the x-axis or a y-axis metric."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth knowing rather than a change request: these three warnings only reach the caller from generate_chart, which pops _mcp_warnings into the response at superset/mcp_service/chart/tool/generate_chart.py:333. update_chart and update_chart_preview discard them instead (update_chart.py:376 and update_chart_preview.py:241), so update_chart on a chart that already has a group_by accepts sort_by, applies nothing and says nothing.

The discard predates this PR, but these are the first _mcp_warnings a user would actually act on, so it may be worth carrying them through on the update path as well.

@FrancescoCastaldi

Copy link
Copy Markdown
Contributor Author

Addressed review suggestions in commit fca3591:

  1. superset/mcp_service/chart/schemas.py: updated XYChartConfig.sort_by annotation to SortByConfig | str | Tuple[str, bool] | Annotated[List[SortByConfig | str], Field(max_length=1)] | None. This ensures [col, asc] validates cleanly against Draft202012Validator and advertises the single-sort-column constraint (maxItems=1) in the generated JSON schema.
  2. tests/unit_tests/mcp_service/chart/test_chart_schemas.py: added test_sort_by_pair_format_valid_against_json_schema to verify schema validation for the pair format.

Comment thread superset/mcp_service/chart/schemas.py Resolved
Add OmittedMeansUnchanged to SortByConfig bases so that its optional
saved_metric field conforms with the null schema defaults ban introduced
in apache#44573.

Signed-off-by: Francesco Castaldi <info@francescocastaldi.it>
@FrancescoCastaldi

Copy link
Copy Markdown
Contributor Author

@aminghadersohi merged master to bring in #44573 and updated SortByConfig bases to include OmittedMeansUnchanged in commit ee9a0b4.

@bito-code-review

bito-code-review Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #d2e8b3

Actionable Suggestions - 0
Review Details
  • Files reviewed - 2 · Commit Range: 251ef2c..ee9a0b4
    • superset/mcp_service/chart/schemas.py
    • tests/unit_tests/mcp_service/chart/test_chart_schemas.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - 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 documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Oct 9, 2026
@FrancescoCastaldi

Copy link
Copy Markdown
Contributor Author

Hi @rusackas, @aminghadersohi,

I have merged the latest upstream master into this branch (commit 0f4150b) and resolved all upstream sync conflicts cleanly. The full unit test suite passes green. The branch is up to date and ready for merge whenever you have a chance.

Thanks!
Francesco

@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt PR Risk: Low Risk

  • The PR appears safe to merge; it adds XY sort_by support while preserving existing sorting behavior when sort_by is omitted.
  • Temporal and grouped charts avoid applying unsupported sorts, and tests cover metric labels, saved metrics, validation, and query ordering.

Assessed commit: d8a08f65f871

@aminghadersohi aminghadersohi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conflict resolution is correct; two merge leftovers fail unit-tests and pre-commit (current) at this head (inline).

order_desc if order_desc is not None else form_data.get("order_desc", True)
)
qd["orderby"] = [(sort_metric, not descending)]
elif (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unreachable since #43771: XY charts no longer call build_single_query_dict, and its four plugin callers never set x_axis_sort or is_timeseries. Consider dropping this branch, _resolve_x_axis_sort_target and the new param.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, please drop it, together with its build_single_query_dict x_axis_sort tests; XY sort is already covered through build_query_dicts_from_form_data.

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Oct 9, 2026
@FrancescoCastaldi

Copy link
Copy Markdown
Contributor Author

Thanks @aminghadersohi for catching both merge leftovers.

Both points have been resolved in commit d8a08f6:

  1. Removed the extra third blank line in superset/mcp_service/chart/chart_helpers.py, bringing it back to standard PEP 8 spacing so ruff format --check passes cleanly.
  2. Updated test_build_query_dicts_from_form_data_xy_bar_explore_default_grain in tests/unit_tests/mcp_service/chart/test_chart_helpers.py to validate against the post-PR feat(mcp): add typed Sunburst chart support #43771 contract, checking the axis dict column structure and the sort operator inside post_processing.

Regarding build_single_query_dict: good catch that XY charts now flow entirely through form_data_query_context via build_query_objects_from_form_data. If you prefer pruning that branch and helper from build_single_query_dict completely, let me know and I will gladly drop it.

All relevant unit tests (337 schema and util tests, plus all sort tests) pass locally.

@aminghadersohi aminghadersohi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Findings from my earlier review are addressed at this head, and the tool-inventory budget test passes. Approving.

@aminghadersohi
aminghadersohi merged commit 64b02ee into apache:master Oct 10, 2026
71 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP: XYChartConfig has no sort option — bar charts created via MCP are always ordered by category name

4 participants