Repository navigation
fix(mcp): add sort_by option to XYChartConfig (#42627) #44464
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
576ade7
342e3fd
75830ec
2d8474d
c5d8d20
00cf542
5ee2ebc
c22ccc3
1ce4027
7cee031
c3df883
91d10c4
2495731
2b8c015
cc590bb
804d291
02dbf36
55c19e3
ff3dc4e
fdb3ea5
81af1e5
a8ab8a7
bc6d9ff
4f996ea
916ffe2
81a94cc
db5e1b4
251ef2c
9df716b
fca3591
65886f3
ee9a0b4
0f4150b
d8a08f6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1291,6 +1291,111 @@ def add_orientation_config(form_data: Dict[str, Any], config: XYChartConfig) -> | |
| form_data["orientation"] = config.orientation | ||
|
|
||
|
|
||
| def _match_y_metric_label(y_cols: list[ColumnRef], sort_lower: str) -> str | None: | ||
| """Find matching metric label for sort_by among Y-axis metrics.""" | ||
| aggregate_aliases = {"STDDEV": "STDDEV_SAMP", "VAR": "VAR_SAMP"} | ||
| for y_col in y_cols: | ||
| metric_obj = create_metric_object(y_col) | ||
| metric_label = ( | ||
| metric_obj | ||
| if isinstance(metric_obj, str) | ||
| else (metric_obj.get("label") or "") | ||
| ) | ||
| agg = y_col.aggregate or "" | ||
| norm_agg = aggregate_aliases.get(agg.upper(), agg.upper()) | ||
| col_name = (y_col.name or "").lower() | ||
| col_label = (y_col.label or "").lower() | ||
| sql_expr = (y_col.sql_expression or "").lower() | ||
| metric_label_lower = metric_label.lower() | ||
|
|
||
| agg_matches: set[str] = set() | ||
| if agg and y_col.name: | ||
| agg_matches.add(f"{agg}({y_col.name})".lower()) | ||
| if norm_agg and y_col.name: | ||
| agg_matches.add(f"{norm_agg}({y_col.name})".lower()) | ||
|
|
||
| if ( | ||
| sort_lower == col_name | ||
| or sort_lower == metric_label_lower | ||
| or (col_label and sort_lower == col_label) | ||
| or (sort_lower in agg_matches) | ||
| or (sql_expr and sort_lower == sql_expr) | ||
| ): | ||
| return metric_label | ||
| return None | ||
|
|
||
|
|
||
| def add_xy_sort_config( | ||
| form_data: Dict[str, Any], config: XYChartConfig, x_is_temporal: bool | ||
| ) -> None: | ||
| """Apply sort configuration to form_data for XY charts. | ||
|
|
||
| When ``config.sort_by`` is present: | ||
| - If ``x_is_temporal``: records a warning in ``form_data["_mcp_warnings"]`` | ||
| and does not override temporal sorting. | ||
| - If ``group_by`` is set: records a warning and ignores ``sort_by`` because | ||
| x-axis sort applies only to single-series charts in Superset. | ||
| - If the sort target does not match the x-axis column or a y-axis metric: | ||
| records a warning and does not apply ``x_axis_sort``. | ||
| - If valid and non-temporal: resolves the sort target to the corresponding | ||
| metric label (or dimension column name) and sets ``form_data["x_axis_sort"]`` | ||
| and ``form_data["x_axis_sort_asc"]``. | ||
| When ``config.sort_by`` is not specified, maintains existing default behavior. | ||
| """ | ||
| if not config.sort_by: | ||
| return | ||
|
|
||
| sort_entry = config.sort_by | ||
| if not isinstance(sort_entry, SortByConfig): | ||
| from superset.mcp_service.chart.schemas import _coerce_sort_item | ||
|
|
||
| coerced = _coerce_sort_item(sort_entry) | ||
| if not isinstance(coerced, SortByConfig): | ||
| return | ||
| sort_entry = coerced | ||
|
|
||
| if x_is_temporal: | ||
| x_name = config.x.name if config.x else "x" | ||
| form_data.setdefault("_mcp_warnings", []).append( | ||
| f"sort_by='{sort_entry.column}' was ignored because the x-axis " | ||
| f"column '{x_name}' is temporal. Temporal charts sort " | ||
| f"chronologically by the time axis." | ||
| ) | ||
| return | ||
|
|
||
|
aminghadersohi marked this conversation as resolved.
Resolved
|
||
| if form_data.get("groupby"): | ||
| form_data.setdefault("_mcp_warnings", []).append( | ||
| f"sort_by='{sort_entry.column}' was ignored because group_by is " | ||
| "set; the x-axis sort applies only to single-series charts." | ||
| ) | ||
| return | ||
|
|
||
| sort_lower = sort_entry.column.lower() | ||
| x_name = (config.x.name or "").lower() if config.x else None | ||
| x_label = (config.x.label or "").lower() if config.x else None | ||
|
|
||
| # If sorting by the x-axis dimension itself (case-insensitive check) | ||
| if config.x and ( | ||
| (x_name and sort_lower == x_name) or (x_label and sort_lower == x_label) | ||
| ): | ||
| sort_target = config.x.name or config.x.label | ||
| else: | ||
| # Match against y metrics (by column name, metric label, agg expr, or sql) | ||
| matched_label = _match_y_metric_label(config.y, sort_lower) | ||
| 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." | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 The discard predates this PR, but these are the first |
||
| ) | ||
| return | ||
| sort_target = matched_label | ||
|
|
||
| form_data["x_axis_sort"] = sort_target | ||
| form_data["x_axis_sort_asc"] = sort_entry.ascending | ||
| form_data.pop("x_axis_sort_series_type", None) | ||
| form_data.pop("x_axis_sort_series_ascending", None) | ||
|
|
||
|
|
||
| def configure_temporal_handling( | ||
| form_data: Dict[str, Any], | ||
| x_is_temporal: bool, | ||
|
|
@@ -1617,6 +1722,7 @@ def map_xy_config( # noqa: C901 | |
| add_color_scheme(form_data, config.color_scheme) | ||
| add_currency_format(form_data, config.currency_format) | ||
| add_xy_data_label_options(form_data, config, x_is_temporal) | ||
| add_xy_sort_config(form_data, config, x_is_temporal) | ||
|
|
||
| return form_data | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,12 +26,14 @@ | |
| from superset.mcp_service.chart.chart_utils import ( | ||
| _xy_chart_context, | ||
| _xy_chart_what, | ||
| create_metric_object, | ||
| map_xy_config, | ||
| ) | ||
| from superset.mcp_service.chart.plugin import BaseChartPlugin | ||
| from superset.mcp_service.chart.schemas import ( | ||
| ChartError, | ||
| ColumnRef, | ||
| SortByConfig, | ||
| VegaLitePreview, | ||
| XYChartConfig, | ||
| ) | ||
|
|
@@ -47,6 +49,149 @@ | |
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _match_y_metric_name(raw_lower: str, y_configs: list[dict[str, Any]]) -> str | None: | ||
| for y_col in y_configs: | ||
| if y_col.get("label") and y_col["label"].lower() == raw_lower: | ||
| return y_col["label"] | ||
| if y_col.get("name") and y_col["name"].lower() == raw_lower: | ||
| return y_col.get("label") or y_col["name"] | ||
| if y_col.get("sql_expression") and y_col["sql_expression"].lower() == raw_lower: | ||
| return y_col.get("label") or y_col["sql_expression"] | ||
| agg = y_col.get("aggregate") | ||
| name = y_col.get("name") | ||
| if agg and name and f"{agg}({name})".lower() == raw_lower: | ||
| return y_col.get("label") or f"{agg.upper()}({name})" | ||
| return None | ||
|
|
||
|
|
||
| def _resolve_xy_sort_name_and_metric_status( | ||
| raw_name: str, config_dict: dict[str, Any], dataset_context: Any | ||
| ) -> tuple[str, bool]: | ||
| raw_lower = raw_name.lower() | ||
| if matched_y := _match_y_metric_name(raw_lower, config_dict.get("y") or []): | ||
| return matched_y, False | ||
|
|
||
| x_col = config_dict.get("x") | ||
| if isinstance(x_col, dict): | ||
| if x_col.get("label") and x_col["label"].lower() == raw_lower: | ||
| return x_col["label"], False | ||
| if x_col.get("name") and x_col["name"].lower() == raw_lower: | ||
| return ( | ||
| DatasetValidator.get_canonical_column_name( | ||
| x_col["name"], dataset_context | ||
| ), | ||
| False, | ||
| ) | ||
|
|
||
| if dataset_context and getattr(dataset_context, "available_metrics", None): | ||
| for m in dataset_context.available_metrics: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 The contract itself looks right to me, since |
||
| if m.get("name") and m["name"].lower() == raw_lower: | ||
| return ( | ||
| DatasetValidator.get_canonical_metric_name( | ||
| raw_name, dataset_context | ||
| ), | ||
| True, | ||
| ) | ||
|
|
||
| return DatasetValidator.get_canonical_column_name(raw_name, dataset_context), False | ||
|
|
||
|
|
||
| def _update_sort_by_column( | ||
| sort_item: Any, | ||
| config_dict: dict[str, Any], | ||
| dataset_context: Any, | ||
| ) -> Any: | ||
| if isinstance(sort_item, dict) and "column" in sort_item: | ||
| canonical_name, is_saved = _resolve_xy_sort_name_and_metric_status( | ||
| sort_item["column"], config_dict, dataset_context | ||
| ) | ||
| sort_item["column"] = canonical_name | ||
| if is_saved: | ||
| sort_item["saved_metric"] = True | ||
| return sort_item | ||
| if isinstance(sort_item, str): | ||
| canonical_name, is_saved = _resolve_xy_sort_name_and_metric_status( | ||
| sort_item, config_dict, dataset_context | ||
| ) | ||
| return { | ||
| "column": canonical_name, | ||
| "ascending": False, | ||
| "saved_metric": is_saved or None, | ||
| } | ||
| if isinstance(sort_item, SortByConfig): | ||
| canonical_name, is_saved = _resolve_xy_sort_name_and_metric_status( | ||
| sort_item.column, config_dict, dataset_context | ||
| ) | ||
| return SortByConfig( | ||
| column=canonical_name, | ||
| ascending=sort_item.ascending, | ||
| saved_metric=sort_item.saved_metric or (True if is_saved else None), | ||
| ) | ||
| return sort_item | ||
|
|
||
|
|
||
| def _normalize_xy_sort_by(config_dict: dict[str, Any], dataset_context: Any) -> None: | ||
| """Resolve canonical column or metric name for sort_by in XY charts.""" | ||
| if not (sort_by := config_dict.get("sort_by")): | ||
| return | ||
|
|
||
| if isinstance(sort_by, list): | ||
| if sort_by: | ||
| sort_by[0] = _update_sort_by_column( | ||
| sort_by[0], config_dict, dataset_context | ||
| ) | ||
| else: | ||
| config_dict["sort_by"] = _update_sort_by_column( | ||
| sort_by, config_dict, dataset_context | ||
| ) | ||
|
|
||
|
|
||
| def _extract_sort_col_info(sort_entry: Any) -> tuple[str | None, bool]: | ||
| if isinstance(sort_entry, (list, tuple)) and sort_entry: | ||
| sort_entry = sort_entry[0] | ||
| if isinstance(sort_entry, SortByConfig): | ||
| return sort_entry.column, bool(sort_entry.saved_metric) | ||
| if isinstance(sort_entry, str): | ||
| return sort_entry, False | ||
| if isinstance(sort_entry, dict): | ||
| return sort_entry.get("column"), bool(sort_entry.get("saved_metric")) | ||
| return None, False | ||
|
|
||
|
|
||
| def _add_column_ref_names(ref: ColumnRef | None, names: set[str]) -> None: | ||
| """Add lowercase name, label, and sql_expression of a column ref to names.""" | ||
| if not ref: | ||
| return | ||
| if ref.name: | ||
| names.add(ref.name.lower()) | ||
| if ref.label: | ||
| names.add(ref.label.lower()) | ||
| if ref.sql_expression: | ||
| names.add(ref.sql_expression.lower()) | ||
|
|
||
|
|
||
| def _collect_y_metric_names(y_cols: list[ColumnRef] | None) -> set[str]: | ||
| names: set[str] = set() | ||
| for y_col in y_cols or []: | ||
| _add_column_ref_names(y_col, names) | ||
| if y_col.aggregate and y_col.name: | ||
| names.add(f"{y_col.aggregate}({y_col.name})".lower()) | ||
| metric_obj = create_metric_object(y_col) | ||
| label = metric_obj if isinstance(metric_obj, str) else metric_obj.get("label") | ||
| if label: | ||
| names.add(label.lower()) | ||
| return names | ||
|
|
||
|
|
||
| def _get_covered_xy_names(config: XYChartConfig) -> set[str]: | ||
| """Collect lowercase names and labels already covered in x, y, and group_by.""" | ||
| covered = _collect_y_metric_names(config.y) | ||
| _add_column_ref_names(config.x, covered) | ||
| for gb in config.group_by or []: | ||
| _add_column_ref_names(gb, covered) | ||
| return covered | ||
|
|
||
|
|
||
| class XYChartPlugin(BaseChartPlugin): | ||
| """Plugin for xy chart type (line, bar, area, scatter).""" | ||
|
|
||
|
|
@@ -123,6 +268,14 @@ def extract_column_refs(self, config: Any) -> list[ColumnRef]: | |
| if config.filters: | ||
| for f in config.filters: | ||
| refs.append(ColumnRef(name=f.column)) | ||
| if config.sort_by: | ||
| sort_col, is_saved = _extract_sort_col_info(config.sort_by) | ||
| # Do not emit a separate column ref if sort_col refers to a | ||
| # column or metric already represented in x, y, or group_by. | ||
| # In particular, metric labels (e.g. "SUM(sales)") or custom labels | ||
| # are not physical dataset columns and would fail validation. | ||
| if sort_col and sort_col.lower() not in _get_covered_xy_names(config): | ||
| refs.append(ColumnRef(name=sort_col, saved_metric=is_saved)) | ||
| return refs | ||
|
|
||
| def to_form_data( | ||
|
|
@@ -155,6 +308,8 @@ def normalize_column_refs(self, config: Any, dataset_context: Any) -> Any: | |
| for gb_col in config_dict.get("group_by") or []: | ||
| gb_col["name"] = get_canonical(gb_col["name"], dataset_context) | ||
|
|
||
| _normalize_xy_sort_by(config_dict, dataset_context) | ||
|
|
||
| DatasetValidator.normalize_filters(config_dict, dataset_context) | ||
| return XYChartConfig.model_validate(config_dict) | ||
|
|
||
|
|
||
There was a problem hiding this comment.
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 setx_axis_sortoris_timeseries. Consider dropping this branch,_resolve_x_axis_sort_targetand the new param.There was a problem hiding this comment.
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_dictx_axis_sort tests; XY sort is already covered throughbuild_query_dicts_from_form_data.