Repository navigation
fix(mcp): add sort_by option to XYChartConfig (#42627) - #44464
Conversation
Code Review Agent Run #7839c0Actionable Suggestions - 0Additional Suggestions - 2
Filtered by Review RulesBito filtered these suggestions based on rules created automatically for your feedback. Manage rules.
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
| 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)) |
There was a problem hiding this comment.
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
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 fixThere was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
Thanks for the review and suggestions! This is now fully resolved and verified across the pipeline as of fdb3ea5:
extract_column_refschecks covered XY names (including x-axis, group-by, and y-axis metrics/labels and SQL expressions), skipping redundantColumnRefadditions that previously triggered premature validation failures.- Saved metrics and SQL expression metrics are resolved against
dataset_context.available_metricswithsaved_metric=True. - End-to-end integration tests were added in
TestValidationPipelineWithXYChartSortByto ensuresort_bytraversesValidationPipelineand setsform_data["x_axis_sort"], correctly resolving to metric labels (e.g.SUM(sales)).
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
| 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) |
There was a problem hiding this comment.
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
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 fixThere was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
✅ 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.
b8aa3be to
f396a3b
Compare
Code Review Agent Run #9bbe55Actionable Suggestions - 0Additional Suggestions - 3
Filtered by Review RulesBito filtered these suggestions based on rules created automatically for your feedback. Manage rules.
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
gabotorresruiz
left a comment
There was a problem hiding this comment.
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:
sortOperatorwithmetrics: [SUM(amount)]andx_axis_sort: 'amount'returnsundefined, for bothx_axis_sort_ascvalues. The same call withx_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_warningsrejectssort_by: "SUM(amount)"withColumn 'SUM(amount)' not found in dataset, rejects a custom metriclabel, and rejects a saved metric name with'count' matches a saved metric but the ref doesn't have saved_metric=true. That happens becauseextract_column_refsadds the sort target as a plainColumnRef(superset/mcp_service/chart/plugins/xy.py:129-143) and dataset validation runs beforenormalize_column_refs. The CodeAnt bot flagged the same root cause onxy.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_targetextract_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
left a comment
There was a problem hiding this comment.
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.
…column validation
…ng in chart utils
…gainst dataset context
f396a3b to
91d10c4
Compare
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
… in add_xy_sort_config
…sitive and sql metric matching
… match, groupby warning, temporal gate
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.
|
@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 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. |
Code Review Agent Run #73a434Actionable Suggestions - 0Additional Suggestions - 1
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
|
@aminghadersohi / @gabotorresruiz please take another spin and see how it looks now :D |
|
Heya @FrancescoCastaldi, LGTM still stands on the content. Looks like a big MCP refactor merged to |
…mcp-xy-chart-sort-by
|
Thanks @rusackas! All set, rebased and merged with Resolved the conflicts in Ready for merge whenever you're good! |
gabotorresruiz
left a comment
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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?
| ge=1, | ||
| le=10000, | ||
| ) | ||
| sort_by: SortByConfig | str | List[SortByConfig | str] | None = Field( |
There was a problem hiding this comment.
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." |
There was a problem hiding this comment.
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.
|
Addressed review suggestions in commit fca3591:
|
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>
|
@aminghadersohi merged master to bring in #44573 and updated SortByConfig bases to include OmittedMeansUnchanged in commit ee9a0b4. |
Code Review Agent Run #d2e8b3Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
|
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! |
CodeAnt PR Risk: Low Risk
Assessed commit: |
aminghadersohi
left a comment
There was a problem hiding this comment.
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 ( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
…x ruff formatting
|
Thanks @aminghadersohi for catching both merge leftovers. Both points have been resolved in commit d8a08f6:
Regarding All relevant unit tests (337 schema and util tests, plus all sort tests) pass locally. |
aminghadersohi
left a comment
There was a problem hiding this comment.
Findings from my earlier review are addressed at this head, and the tool-inventory budget test passes. Approving.
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"andx_axis_sort_series_ascending = True).This PR adds comprehensive sorting support via the
sort_byfield toXYChartConfig:sort_by: SortByConfig | str | List[SortByConfig | str] | NonetoXYChartConfigwith aliases (x_axis_sort,order_by,order_by_cols).[col, asc], and single-item lists (defaulting bare strings to descending order, and rejecting multi-column lists).saved_metric: bool | NonetoSortByConfigto track and preserve metric status across validation stages.add_xy_sort_configinchart_utils.py):x_axis_sortandx_axis_sort_asc, alongside backward-compatibility keysx_axis_sort_series_type("name"if sorting by x-axis dimension,"value"otherwise) andx_axis_sort_series_ascending.sql_expression/sqlExpression).sort_bywith a warning inform_data["_mcp_warnings"].XYChartPlugininxy.py):dataset_context.available_metricswhen not explicitly present in Y metrics, markingsaved_metric=True.ColumnRef(name=sort_col, saved_metric=is_saved)soDatasetValidator._validate_columns_existpasses without rejecting independent saved metrics._resolve_x_axis_sort_targetinchart_helpers.py):form_data["metrics"], matching by label, column name, orsqlExpressioncase-insensitively, and setsqueries[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.pyAll tests pass (1916 passed across MCP chart test suite), covering:
ADDITIONAL INFORMATION