Skip to content

fix(mcp): use chart metrics for the preview y axis - #44684

Merged
aminghadersohi merged 4 commits into
apache:masterfrom
aminghadersohi:fix/mcp-preview-y-axis
Sep 28, 2026
Merged

aminghadersohi merged 4 commits into
apache:masterfrom
aminghadersohi:fix/mcp-preview-y-axis

Conversation

@aminghadersohi

Copy link
Copy Markdown
Contributor

SUMMARY

The MCP chart preview built its Vega-Lite y encoding from the first column whose name looked like an aggregate or whose value looked numeric. Because Python bool is a subclass of int, a boolean x-axis column could be picked as the y field, and in general the y field was not guaranteed to be one of the chart's metrics.

This change resolves the y field from the chart's metrics in form_data, using their result labels (same rules as metric_result_label) and picking the first one present in the result columns. The previous heuristic is kept only as a fallback when no metric label matches, and it no longer treats boolean values as numeric.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A (backend preview spec change)

TESTING INSTRUCTIONS

pytest tests/unit_tests/mcp_service/chart/test_preview_utils.py

New tests cover: boolean x column with a numeric metric (y is the metric), multiple metrics (first matching metric is used), metrics with no matching label (fallback skips booleans), and no metrics (no y encoding, unchanged).

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • 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

🤖 Generated with Claude Code

Choose the Vega-Lite preview y field from the chart's metric labels
instead of the first numeric-looking column. The previous heuristic is
kept as a fallback when no metric label matches, and boolean values are
no longer treated as numeric.
@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #454e74

Actionable Suggestions - 0
Additional Suggestions - 1
  • superset/mcp_service/chart/preview_utils.py - 1
    • Loose substring metric match · Line 1274-1278
      `agg in str(col).upper()` is a substring test, so a dimension column such as `COUNTY` (matches `COUNT`) or `MINIMUM` (matches `MIN`) is returned as the y-axis metric on the fallback path, yielding a wrong chart. Prefer a whole-token match. Note this heuristic is only reached when no metric label matches.
Filtered by Review Rules

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

  • superset/mcp_service/chart/preview_utils.py - 1
Review Details
  • Files reviewed - 2 · Commit Range: edcb263..edcb263
    • superset/mcp_service/chart/preview_utils.py
    • tests/unit_tests/mcp_service/chart/test_preview_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 [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@codecov

codecov Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.88889% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.20%. Comparing base (5b9733f) to head (a8c9ed3).
⚠️ Report is 21 commits behind head on master.

Files with missing lines Patch % Lines
superset/mcp_service/chart/preview_utils.py 88.88% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #44684      +/-   ##
==========================================
+ Coverage   81.12%   81.20%   +0.07%     
==========================================
  Files        2956     2961       +5     
  Lines      178434   178931     +497     
  Branches    41339    41406      +67     
==========================================
+ Hits       144762   145293     +531     
+ Misses      30967    30921      -46     
- Partials     2705     2717      +12     
Flag Coverage Δ
hive 36.72% <16.66%> (-0.06%) ⬇️
mysql 56.06% <16.66%> (+0.09%) ⬆️
postgres 56.07% <16.66%> (+0.08%) ⬆️
presto 38.62% <16.66%> (-0.07%) ⬇️
python 85.53% <88.88%> (+0.11%) ⬆️
sqlite 55.79% <16.66%> (+0.09%) ⬆️
unit 77.83% <88.88%> (+0.12%) ⬆️

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.

@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Sep 27, 2026
@netlify

netlify Bot commented Sep 27, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 9bd6964
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ab86c583466ee0008f869fc
😎 Deploy Preview https://deploy-preview-44684--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.

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #aaa115

Actionable Suggestions - 0
Filtered by Review Rules

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

  • superset/mcp_service/chart/preview_utils.py - 2
Review Details
  • Files reviewed - 3 · Commit Range: edcb263..9bd6964
    • docs/admin_docs/configuration/mcp-server.mdx
    • superset/mcp_service/chart/preview_utils.py
    • tests/unit_tests/mcp_service/chart/test_preview_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 [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@rebenitez1802 rebenitez1802 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.

Approve — genuine improvement (kills the bool-as-int misclassification and ties the y-axis to the chart's actual metrics), security-neutral, and correctly tested for the numeric types real previews carry. Only optional nits below.

🟢 Low — Numeric gate is narrower than the sibling treemap validator
_resolve_y_metric_column gates on isinstance(value, (int, float)) and not isinstance(value, bool) (preview_utils.py:1273-1274, 1281-1282), whereas the treemap validator in the same module uses isinstance(value, (Real, Decimal)) (query_result.py:321) precisely because SQL NUMERIC/DECIMAL results (e.g. Postgres AVG/SUM) arrive as decimal.Decimal. This is not a real preview regression: the preview data comes from ChartDataCommand.run(), whose pipeline runs df_metrics_to_num (normalize_df → common/utils/dataframe_utils.py:62, enforce_numerical_metrics=True by default), coercing object-dtype metric columns to native float64 before df.to_dict("records") — a Decimal("7") SUM(amount) column becomes native float 7.0 at the resolver, so the gate passes and the y-axis is set. The only uncoerced path is the fallback loop over all columns (1281-1282), which df_metrics_to_num doesn't touch for non-metric dimensions — a marginal edge. Matching the treemap validator's (Real, Decimal) is a cheap consistency/robustness win; reasonable to take or skip. Fix (if taken): add from decimal import Decimal / from numbers import Real and use isinstance(value, (Real, Decimal)) and not isinstance(value, bool) in both checks.

🟢 Low — _resolve_y_metric_column return type is Any
The helper only ever returns str | None (a column label or None), but is annotated -> Any (preview_utils.py:1260). Tightening it documents the contract and gives mypy narrowing at the if metric_col: call site (1355). Fix: def _resolve_y_metric_column(row: Dict[str, Any], metrics: List[Any]) -> str | None:.

Verified, no change needed: the matched_metric early-None correctly still lets a later numeric metric win over an earlier non-numeric one (covered by test_vega_preview_y_axis_skips_nonnumeric_metrics); the numpy-scalar concern is moot (pandas 2.3.3 to_dict boxes np.int64/np.float64 to native types); the pie/theta and x==y fallback edges are pre-existing (untouched by this PR); the docs section accurately describes the code; and the change is out of security scope — read-only display-spec construction on already-authorized chart data, no auth/query/data-access boundary touched.

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Taken both nits in a8c9ed3: both numeric checks use Real/Decimal (excluding bool), with a Decimal fallback regression test, and the return type is str | None. Chart tests: 2,153 passed, 3 skipped; pre-commit passed.

@aminghadersohi
aminghadersohi merged commit f6d9b7b into apache:master Sep 28, 2026
72 checks passed
@bito-code-review

Copy link
Copy Markdown
Contributor

Bito Automatic Review Skipped – PR Already Merged

Bito scheduled an automatic review for this pull request, but the review was skipped because this PR was merged before the review could be run.
No action is needed if you didn't intend to review it. To get a review, you can type /review in a comment and save it

villebro pushed a commit that referenced this pull request Sep 30, 2026
villebro added a commit that referenced this pull request Sep 30, 2026
The y-axis metric tests cherry-picked from #44684 use
pytest.mark.parametrize, but on 7.0 test_preview_utils.py never imported
pytest: on master that import arrived with the bubble/Gantt preview tests
(#43572/#43737), which are not on 7.0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

doc Namespace | Anything related to documentation size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants