Skip to content

feat(mcp): bubble chart type plugin - #43572

Merged
rusackas merged 4 commits into
apache:masterfrom
gkneighb:feat/mcp-bubble-plugin
Sep 21, 2026
Merged

rusackas merged 4 commits into
apache:masterfrom
gkneighb:feat/mcp-bubble-plugin

Conversation

@gkneighb

@gkneighb gkneighb commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

Adds a generate_chart MCP plugin for the bubble chart type (viz_type: bubble_v2), so the MCP generate_chart tool can produce bubble charts. Bubble is a shipped Superset viz type that had no MCP plugin; this closes that gap.

The plugin mirrors the frontend Bubble buildQuery contract: an entity dimension identifies each bubble, three separate metrics position and size it (x horizontal, y vertical, size area), and an optional series dimension colours the bubbles by group.

Follows the established plugin pattern (pie/funnel/gauge/treemap/heatmap/radar/waterfall) — a config schema, a map_*_config mapper, a plugin class, and registration:

  • BubbleChartConfig — entity, x, y, and size required; optional series, row_limit (default 10000), filters, color_scheme. Added to the ChartConfig discriminated union and the get_chart_type_schema adapters. x/y/size are three separate metric keys (the query layer aliases them into metrics), not a metrics array; entity/series may not be saved_metric/sql_expression (dimensions, not metrics).
  • map_bubble_config — maps the config to form_data; saved metrics pass through as bare name strings, ad-hoc metrics as SIMPLE/SQL adhoc objects. series is omitted from form_data when unset.
  • BubbleChartPlugin — registered in the plugin registry. Only the legacy bubble key was in the recommendation category map, so this adds bubble_v2 → bubble.

The field set is intentionally minimal (core query contract). Cosmetic controls (max bubble size, axis labels/formats/bounds, log scales, opacity) are left for a follow-up.

Review surfaced four defects that this PR also fixes, three of them in shared code bubble is the first type to exercise:

  • Shared analyzers assumed a list-valued y. Bubble is the first config in the union whose y is a single column, so analyze_chart_capabilities raised TypeError: object of type 'ColumnRef' has no len() and analyze_chart_semantics iterated the model into (field, value) tuples. generate_chart calls both unguarded, and with save_chart=True the chart row is created before the crash — so the user got an orphaned chart and no URL. Both sites now accept either shape.
  • The implicit aggregate escaped validation. create_metric_object defaults a bare column to SUM, but the ref reported is_metric False, so the aggregate-compatibility check skipped it: x={"name": "country"} on a VARCHAR column sent SUM(country) to the database while spelling out that same SUM was rejected up front. The config now records the default, which routes it through the existing check.
  • A saved chart's sort metric was dropped. Bubble's buildQuery pairs form_data['orderby'] with the negated order_desc flag (default descending). The MCP path builds query dicts directly and never read it, so row_limit truncated an unordered result — a row_limit=1 chart showed an arbitrary bubble rather than the largest.
  • The Vega-Lite preview was an empty bar. The generic spec builder reads x_axis/metrics/groupby, none of which bubble form_data carries, so the advertised preview fell back to a bar mark with no encoding at all. Bubble now gets a circle mark with x/y position, size area, and series (or entity) color.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A — backend/MCP only, no UI change.

TESTING INSTRUCTIONS

pytest tests/unit_tests/mcp_service/chart/test_bubble_chart.py — 37 focused unit tests cover schema validation (four required fields, entity/series not-a-metric, saved-metric axis accepted, extra-field rejection), ChartConfig union dispatch, form_data mapping (three separate metric keys, series omitted when unset, saved-metric passthrough), and registry integration (registration, resolve_viz_type, display_name, pre_validate, recommendation category).

To exercise end-to-end: call the generate_chart MCP tool with
{"chart_type": "bubble_v2", "entity": {"name": "country"}, "x": {"name": "gdp", "aggregate": "AVG"}, "y": {"name": "life_expectancy", "aggregate": "AVG"}, "size": {"name": "population", "aggregate": "SUM"}}.

ADDITIONAL INFORMATION

  • Has associated issue: SC-119154
  • 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

@codecov

codecov Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.51020% with 36 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.56%. Comparing base (a7dab4a) to head (c825e07).

Files with missing lines Patch % Lines
superset/mcp_service/chart/plugins/bubble.py 51.61% 22 Missing and 8 partials ⚠️
superset/mcp_service/chart/preview_utils.py 82.60% 0 Missing and 4 partials ⚠️
superset/mcp_service/chart/chart_utils.py 88.88% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #43572      +/-   ##
==========================================
- Coverage   80.57%   80.56%   -0.01%     
==========================================
  Files        2940     2941       +1     
  Lines      175316   175460     +144     
  Branches    40696    40730      +34     
==========================================
+ Hits       141253   141360     +107     
- Misses      31398    31422      +24     
- Partials     2665     2678      +13     
Flag Coverage Δ
hive 37.23% <29.25%> (-0.02%) ⬇️
mysql 56.46% <29.25%> (-0.05%) ⬇️
postgres 56.47% <29.25%> (-0.05%) ⬇️
presto 39.12% <29.25%> (-0.02%) ⬇️
python 84.86% <75.51%> (-0.02%) ⬇️
sqlite 56.19% <29.25%> (-0.05%) ⬇️
unit 76.60% <75.51%> (-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.

@gkneighb
gkneighb force-pushed the feat/mcp-bubble-plugin branch from a76d61c to f89b3b0 Compare August 27, 2026 11:11
@gkneighb
gkneighb marked this pull request as ready for review August 27, 2026 12:05
@dosubot dosubot Bot added change:backend Requires changing the backend viz:charts:bubble Related to the Bubble chart labels Aug 27, 2026
@bito-code-review

Copy link
Copy Markdown
Contributor

The review comment is correct. The BubbleChartConfig validator currently only checks sql_expression and saved_metric for dimensions, allowing aggregate to be passed, which is then silently ignored by the mapper. To resolve this, you should update the reject_metric_style_dimensions validator in superset/mcp_service/chart/schemas.py to also reject the aggregate field on entity and series dimensions.

Here is the corrected validator implementation:

    @model_validator(mode="after")
    def reject_metric_style_dimensions(self) -> "BubbleChartConfig":
        """entity and series are dimensions, not metrics."""
        dims = [(self.entity, "entity")]
        if self.series is not None:
            dims.append((self.series, "series"))
        for col, name in dims:
            _reject_sql_expression_on_dimension(col, name)
            if col.saved_metric:
                raise ValueError(
                    f"{name} cannot use saved_metric=True; "
                    "saved metrics belong in the 'x', 'y', or 'size' fields"
                )
            if col.aggregate:
                raise ValueError(f"{name} cannot use aggregate; dimensions do not support aggregation")
        return self

Would you like me to fetch all other comments on this PR to validate and implement fixes for them as well?

superset/mcp_service/chart/schemas.py

@model_validator(mode="after")
    def reject_metric_style_dimensions(self) -> "BubbleChartConfig":
        """entity and series are dimensions, not metrics."""
        dims = [(self.entity, "entity")]
        if self.series is not None:
            dims.append((self.series, "series"))
        for col, name in dims:
            _reject_sql_expression_on_dimension(col, name)
            if col.saved_metric:
                raise ValueError(
                    f"{name} cannot use saved_metric=True; "
                    "saved metrics belong in the 'x', 'y', or 'size' fields"
                )
            if col.aggregate:
                raise ValueError(f"{name} cannot use aggregate; dimensions do not support aggregation")
        return self

@bito-code-review bito-code-review Bot 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.

Code Review Agent Run #0f8840

Actionable Suggestions - 1
  • tests/unit_tests/mcp_service/chart/test_bubble_chart.py - 1
    • Extra-field test contradicts ignore policy · Line 62-64
Review Details
  • Files reviewed - 7 · Commit Range: f89b3b0..f89b3b0
    • superset/mcp_service/chart/chart_utils.py
    • superset/mcp_service/chart/plugins/__init__.py
    • superset/mcp_service/chart/plugins/bubble.py
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/tool/get_chart_data.py
    • superset/mcp_service/chart/tool/get_chart_type_schema.py
    • tests/unit_tests/mcp_service/chart/test_bubble_chart.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

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

Fifth of the bubble/gauge/treemap/radar plugin family I've reviewed — same house style, thorough tests, clean CI. One thing carries over cleanly, one bot is a false positive, and there's a third issue the two bots didn't surface that I think is the most important one here. Everything below was executed against the PR head in a throwaway worktree (superset_core on PYTHONPATH), not just eye-balled; I mark RAN vs INSPECTED per claim.

1. schemas.py:1108 — CodeAnt's aggregate gap: real, but benign for bubble (RAN)

Confirmed, and byte-identical to the gauge/treemap/radar siblings: reject_metric_style_dimensions rejects sql_expression and saved_metric on entity/series but not aggregate.

entity={"name":"country","aggregate":"SUM"}  -> validates OK
map_bubble_config(...)["entity"] == "country"   # aggregate silently dropped
series={"name":"continent","aggregate":"COUNT"} -> ["series"] == "continent"

Bubble-specific severity: cosmetic / silent-drop — the gauge & radar tier, not treemap's wrong-numbers tier. entity and series are emitted as bare column-name strings that feed groupby; dropping a (meaningless) aggregate on a grouping dimension leaves the grouping intact, does not collapse bubbles, and does not touch the axes — x/y/size are independent metric fields that honor their own aggregates (verified: x.label == "AVG(gdp)" regardless of the entity aggregate). So the generated form_data differs from the literal request, but the resulting chart is what a correctly-specified entity would have produced. Worth closing for family consistency, not a data-correctness bug.

Fix precedent already in the file — reuse ColumnRef.is_metric (schemas.py:751, bool(aggregate) or saved_metric or bool(sql_expression)) in the dimension loop rather than hand-rolling another check.

2. test_bubble_chart.py:64 — Bito's extra-field claim: false positive (RAN)

Bito says model_config = ConfigDict(extra="ignore") makes test_bubble_rejects_extra_fields fail at runtime. It doesn't — I ran the full file, 18 passed, that test included. BaseChartConfig extends UnknownFieldCheckMixin (schemas.py:665), a mode="before" validator that raises for unknown fields regardless of extra="ignore" (and adds "did you mean?" hints). Bito read the ConfigDict and missed the base-class mixin.

Unlike radar — where three tests positively asserted the buggy 1-metric config and cemented the defect — this test pins the correct contract (extra fields rejected). It should stay as-is; no schema change to extra="forbid" needed.

3. Not flagged by either bot: bubble_v2 metrics are dropped in the MCP query path (RAN — headline)

The get_chart_data.py +1 line is just "bubble_v2": "bubble" in _VIZ_CATEGORY (recommendation-category map) — correct and harmless. But it points at the real problem, which is the same "the MCP path rebuilds query context from form_data instead of running the frontend buildQuery" shape that surfaced on funnel and sankey.

resolve_metrics (chart_helpers.py:399 — pre-existing, not in this PR's diff) folds x/y/size into query metrics only for the legacy key:

if viz_type == "bubble":
    return [m for field in ("x", "y", "size") if (m := form_data.get(field))]

But this PR's map_bubble_config emits viz_type: "bubble_v2" (and bubble_v2 is the canonical VizType.Bubble). Running the exact query-dict builder get_chart_data uses:

viz_type: bubble_v2
QUERY columns (groupby): ['country', 'continent']    # resolve_groupby handles entity/series fine
QUERY metrics: []                                    # x/y/size DROPPED
# legacy 'bubble' on the same form_data -> ['AVG(gdp)','AVG(life_expectancy)','SUM(population)']

Reachability (RAN + INSPECTED): generate_chart saves the chart with params=form_data but no query_context (CreateChartCommand is given no query_context). So get_chart_data on a saved MCP bubble chart takes the "no saved query_context" fallback (get_chart_data.py:621) → build_query_dicts_from_form_data → metrics=[]. The safety net at :632 (not metrics and not columns) does not fire because columns=[entity, series] is non-empty, so it proceeds silently. The unsaved form_data_key path (_query_from_form_data) and the _compile_chart preview both extract metrics the same way and hit the same []. Ironically the fallback's own comment (:615, "Bubble charts use x/y/size as separate metric fields") shows the intent was for this to work.

Impact: the chart renders correctly in Explore (the real frontend buildQuery runs there), but the MCP get_chart_data/preview returns a bubble query with all three metrics missing — a bare GROUP BY entity, series with no aggregates. This is a genuine data-correctness bug for the new viz type, higher severity than #1.

Fix: one line, in chart_helpers.py (a file this PR doesn't touch but arguably should) — if viz_type in ("bubble", "bubble_v2"). Please also add a test that drives resolve_metrics / a bubble_v2 form_data through the query-dict builder; nothing in the 18 tests exercises this path, which is why CI is green over it.

Test coverage (Rule 26)

Reverting only the production files fails the schema/mapper/registry unit tests, as expected — but there is no negative test for aggregate on entity/series (only saved_metric rejection is asserted), and no test covering the bubble_v2 query-build path from #3. So both #1 and #3 sit entirely outside the test net. Better than radar (which asserted its bug); still a gap.

Gates (re-derived at post time)

  • CI: 47 SUCCESS / 3 NEUTRAL / 12 SKIPPED / 0 pending / 0 failing (grouped by check name, latest run each).
  • mergeable=MERGEABLE, mergeStateStatus=BLOCKED; head f89b3b00.
  • External contributor + two open bot threads → leaving this as a comment, not an approval, and not resolving either thread.

Nice work overall — the schema/mapper/registry structure is clean and the entity/series-vs-x/y/size split is modeled exactly right. #3 is the one I'd want addressed before merge.

@netlify

netlify Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

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

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

Round 2 — new head 64663058

Thanks for the fast turnaround. Both round-1 findings are fixed exactly as suggested, and you added the regression tests I'd asked for. I re-ran everything against this head in a clean pinned worktree (superset_core on PYTHONPATH); RAN vs INSPECTED marked per claim.

✅ Fix 1 — bubble_v2 metrics data-loss (my headline finding): resolved (RAN)

resolve_metrics now matches ("bubble", "bubble_v2"). Driving the exact query-dict builder get_chart_data uses:

resolve_metrics(fd, "bubble_v2") -> ['AVG(gdp)', 'AVG(life_expectancy)', 'SUM(population)']
build_query_dicts_from_form_data(...) -> metrics=[AVG(gdp), AVG(life_expectancy), SUM(population)], groupby=[country, continent]

No longer metrics=[]. The new test_bubble_v2_metrics_resolved locks it in. 👍

✅ Fix 2 — aggregate on entity/series (codeant thread schemas.py:1109): resolved (RAN)

Switched to col.is_metric (the property I pointed at — bool(aggregate) or saved_metric or bool(sql_expression)). Verified: entity={name:country, aggregate:SUM} and series={…, aggregate:COUNT} now both raise ValidationError with a clear message; valid configs and saved_metric on x/y/size still pass. The two new negative tests close the Rule-26 gap I flagged. Full suite: 21 passed (was 18). codeant's thread is now addressed by this change (I'm leaving the bot thread as-is, not resolving).

ℹ️ bito thread test_bubble_chart.py:64: still a false positive

No change needed — UnknownFieldCheckMixin still rejects unknown fields despite extra="ignore"; the test passes. Flagging only so it's not mistaken for an open item.


🟠 New finding this round — the preview/compile path has the same blind spot the fix didn't reach (RAN + INSPECTED)

The resolve_metrics fix corrects the get_chart_data path, but generate_chart validates via a parallel helper, _compile_chart (superset/mcp_service/chart/compile.py), which does its own extraction and does not know bubble's bespoke keys:

columns = _build_query_columns(form_data)      # -> columns_from_form_data(): reads groupby/columns/x_axis
metrics = form_data.get("metrics", []) or ([form_data["metric"]] if form_data.get("metric") else [])

bubble_v2 form_data has none of groupby/columns/x_axis/metrics/metric — only entity/series/x/y/size. Executed against this head:

_build_query_columns(bubble_v2 fd) -> []          # entity/series not recognized
metric extraction               -> []             # x/y/size not recognized

So _compile_chart builds a QueryContext with empty columns AND empty metrics. That hits the guard at superset/models/helpers.py:4376 (INSPECTED): if not metrics and not columns and not groupby: raise QueryObjectValidationError("Empty query?"). generate_chart treats a failed compile as fatal on both paths — save (generate_chart.py:398→414, "Chart query failed to execute. The chart was not saved.") and preview-only (:610→620).

Consequence (high confidence, not DB-verified): creating a bubble chart via generate_chart likely fails at the compile gate for every input. Contrast map_pie_config, which emits groupby+metric (both read by these helpers) and compiles fine — bubble is the anomaly because its grouping/metrics live in entity/series/x/y/size.

I could execute the extraction (columns=[], metrics=[]) and confirm the guard condition, but not ChartDataCommand.run() end-to-end (no live dataset here), so I've stopped short of calling it confirmed. Could you run generate_chart for a bubble config against a real dataset once to confirm/refute? Nothing in the 21 unit tests exercises _compile_chart/generate_chart, which is why CI is green over this.

This is pre-existing in compile.py/form_data_query_context.py (outside this PR's diff), but it's the same viz-plugin-bespoke-keys shape and it blocks the feature this PR ships. Cleanest fix is to make _compile_chart reuse resolve_metrics/resolve_groupby (single source of truth) instead of its own extraction — that would also prevent this class of drift for the next chart type.


Gates (re-derived at post time): CI 48 SUCCESS / 2 NEUTRAL / 9 SKIPPED / 0 pending / 0 failing (deduped by check name, latest run). mergeable=MERGEABLE, mergeStateStatus=BLOCKED, head 64663058. External contributor → leaving this as a comment, not an approval; not resolving the bot threads. The two round-1 items are genuinely fixed — nice work; the compile-path item above is the one thing I'd verify before merge.

@bito-code-review

bito-code-review Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #5f1a23

Actionable Suggestions - 0
Review Details
  • Files reviewed - 3 · Commit Range: f89b3b0..6466305
    • superset/mcp_service/chart/chart_helpers.py
    • superset/mcp_service/chart/schemas.py
    • tests/unit_tests/mcp_service/chart/test_bubble_chart.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

@gkneighb
gkneighb force-pushed the feat/mcp-bubble-plugin branch from 6466305 to 30ef2c8 Compare August 31, 2026 15:19
@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Aug 31, 2026

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

Round 3 — sign-off retracted (see coordinated review)

Correction (2026-08-31): my earlier round-3 conclusion that there were "no new blockers" was incomplete — a subsequent independent pass over this head found additional blockers (notably: x/y/size accept plain dimension columns that are silently coerced to SUM after aggregate-compatibility validation is skipped; native temporal form-data can't round-trip Generate/Update; and the advertised Vega-Lite preview falls back to an empty spec). Treat those as open. This PR is not clean to merge on the basis of my review.

Second correction — the round-2 finding is NOT fixed at the current head. My round-3 text above credited the _compile_chart fix, but that fix existed only in a commit that has since been reverted; it was never part of your changes. At a8711e00, compile.py is back to extracting metrics = form_data.get("metrics", []) inline, with no shared resolver and no test_compile_builds_non_empty_bubble_query. Treat the round-2 _compile_chart finding as still open. Sorry for the noise — I verified the code at a SHA without checking whose commit it was.

The round-1 fixes DO stand and are yours: bubble_v2 metric resolution (chart_helpers.py:415, commit b7cb85b5) and aggregate/saved_metric rejected on entity/series. This review is otherwise superseded by the ongoing consolidated review. The branch head has since moved and a revert is in progress; re-review against the current head.

@aminghadersohi

Copy link
Copy Markdown
Contributor

sorry i accidentally pushed to your pr. will undo that commit shortly. thank you for your work

@github-actions github-actions Bot removed the doc Namespace | Anything related to documentation label Aug 31, 2026
@aminghadersohi

Copy link
Copy Markdown
Contributor

i put up this pr gkneighb#1 on top of your pr please have a look. it was easier than leaving it comments and better than pushing commit.

@bito-code-review

bito-code-review Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #ca8d39

Actionable Suggestions - 0
Review Details
  • Files reviewed - 8 · Commit Range: 07cd873..a8711e0
    • superset/mcp_service/chart/chart_helpers.py
    • superset/mcp_service/chart/chart_utils.py
    • superset/mcp_service/chart/plugins/__init__.py
    • superset/mcp_service/chart/plugins/bubble.py
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/tool/get_chart_data.py
    • superset/mcp_service/chart/tool/get_chart_type_schema.py
    • tests/unit_tests/mcp_service/chart/test_bubble_chart.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

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

Hey Greg, thanks for the quick turnarounds. I re-verified at this head: the bubble_v2 metric resolution fix and the is_metric rejection both work as advertised (21-test file plus the full chart tree, 1388 passed), and the get_chart_type_schema docstring now lists bubble_v2.

Two items from my pass are still open; the first is blocking and has not been raised in the earlier review rounds. It currently hides behind the _compile_chart issue aminghadersohi flagged (compile fails first when a real dataset is present), so fixing that one alone will surface this one next. Happy to dig in with you on either.

description="Metric for the bubble's horizontal position (use "
"aggregate e.g. AVG, or saved_metric=True for a saved metric)",
)
y: ColumnRef = 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.

This block worries me a bit: BubbleChartConfig is the first config in the union whose y is a single ColumnRef instead of a list, and the shared analyzers duck-type on config.y assuming a list. analyze_chart_capabilities does len(config.y) (chart_utils.py:1734), which raises TypeError: object of type 'ColumnRef' has no len(), and analyze_chart_semantics iterates it (chart_utils.py:1800), yielding (field, value) tuples so col.name raises AttributeError. generate_chart calls both unguarded and its outer except doesn't catch TypeError; with save_chart=True the chart row is created before the crash, so the user also gets an orphaned saved chart. I verified the crash at this head with the PR description's own example config through the real tool harness.

The fix is small; I applied exactly this locally and the full flow completes:

if hasattr(config, "y") and config.y:
    y_refs = config.y if isinstance(config.y, list) else [config.y]
    data_types.extend(["metric"] * len(y_refs))

(same normalization in analyze_chart_semantics). A TestAnalyzeChartCapabilitiesBubble / TestAnalyzeChartSemanticsBubble pair mirroring the big_number ones would lock it in; the current tests cover schema, mapper, and registry but never the generate_chart metadata path.

@@ -291,7 +302,7 @@ def get_chart_type_schema(
for a chart configuration before calling generate_chart or update_chart.

Valid chart_type values depend on the host deployment. Core types are xy,

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.

Follow-through on this docstring fix, not a blocker: the other two LLM-facing enumerations still end at waterfall. The generate_chart docstring's chart_type list and quick lookup have no bubble entry (so a client asked for a bubble chart is steered to chart_type='xy', kind='scatter'), and app.py's "Chart Types You Can CREATE" and registry list omit bubble_v2 even though display_name_for_viz_type("bubble_v2") now resolves. Your waterfall PR (#42070) updated all three, which is what made me look.

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #ce458a

Actionable Suggestions - 0
Additional Suggestions - 4
  • superset/mcp_service/chart/chart_helpers.py - 1
    • orderby direction ignores param · Line 600-603
      The new `elif` branch reads `form_data.get("order_desc", True)` directly, ignoring the `order_desc` parameter of `_build_single_query_dict`. In the fallback path (`get_chart_data.py:616`) `order_desc=True` is hardcoded while form_data may carry `order_desc=False`, so the `orderby` direction contradicts `qd["order_desc"]` and the caller's intent. Use the parameter (falling back to form_data when None).
  • superset/mcp_service/chart/preview_utils.py - 1
    • Duplicate metric resolver · Line 936-944
      `_metric_field_name` duplicates the already-imported `metric_result_label` (query_result.py:97) but is a strict subset: it returns None for SIMPLE metrics without a label and for SQL-expression metrics, where `metric_result_label` resolves a column name. Reuse `metric_result_label` in the channel loop to avoid divergence and silently dropping a bubble channel when form_data lacks a label.
  • tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py - 1
    • Assert analyzer output · Line 1004-1008
      The test verifies the chart is reported but never asserts `result.semantics.data_story`, which is exactly what the fix in `analyze_chart_semantics` (`config.x.name or config.x.label or config.x.sql_expression`) changed. It would still pass if the story silently contained "None". Assert the label is present and "None" is absent to lock in the fix.
  • superset/mcp_service/chart/plugins/bubble.py - 1
    • Redundant dimension guard · Line 108-113
      The `entity`/`series` guard `not col.get("sql_expression") and not col.get("saved_metric")` is always true: `BubbleChartConfig` rejects `sql_expression` and `saved_metric` on dimensions (see `_reject_sql_expression_on_dimension` and the entity/series validator in `schemas.py`). The condition is dead logic that adds confusion; canonicalizing `name` unconditionally is equivalent.
Review Details
  • Files reviewed - 14 · Commit Range: 247adbd..b1b9edb
    • superset/mcp_service/app.py
    • superset/mcp_service/chart/chart_helpers.py
    • superset/mcp_service/chart/chart_utils.py
    • superset/mcp_service/chart/plugins/__init__.py
    • superset/mcp_service/chart/plugins/bubble.py
    • superset/mcp_service/chart/preview_utils.py
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/tool/generate_chart.py
    • superset/mcp_service/chart/tool/get_chart_data.py
    • superset/mcp_service/chart/tool/get_chart_preview.py
    • superset/mcp_service/chart/tool/get_chart_type_schema.py
    • tests/unit_tests/mcp_service/chart/test_bubble_chart.py
    • tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_preview.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

@gkneighb

Copy link
Copy Markdown
Contributor Author

New head edb7e9ff01 picks up three of the four suggestions from the last automated pass. Two of them were real defects in code I added in c5439587, so thanks to whoever tuned that bot — flagging them as non-blocking undersold them.

Sort direction ignored the caller's flag (chart_helpers.py). My orderby branch read form_data.get("order_desc", True) while _build_single_query_dict has its own order_desc parameter that sets qd["order_desc"] a few lines above. get_chart_data passes it explicitly, so a saved order_desc=False plus an explicit order_desc=True produced a query dict that sorted ascending while declaring itself descending. The argument now wins, with form_data as the fallback:

build_query_dicts_from_form_data(fd_with_order_desc_false, ..., order_desc=True)
  -> order_desc True, orderby [(SUM(population), False)]

Unlabeled metrics were dropped from the bubble preview (preview_utils.py). I wrote a local _metric_field_name that only understood an explicit label, when metric_result_label was already imported in the same module (line 31) and handles the cases mine didn't — reconstructing AVG(gdp) from a SIMPLE metric's aggregate plus column, and resolving SQL-expression metrics. For a saved chart whose form_data carries unlabeled metrics, my version returned None and the channel disappeared from the spec entirely; the new test fails with KeyError: 'x' against the old code. The duplicate is gone and the shared resolver is used.

Test strengthened. test_saved_bubble_with_sql_expression_x_is_reported asserted only that the chart came back, so it would have passed with "None" sitting in the data story — the exact thing the previous commit fixed. It now asserts the label is present and "None" is absent.

The fourth suggestion — that the sql_expression/saved_metric guard on entity/series in normalize_column_refs is unreachable because the config validator already rejects both — is correct. I've left it as defensive code rather than grow this diff further; happy to drop it if a reviewer would rather see it go.

For the record on the previous head: the required check was red from the 30-minute job limit again, not a test failure. The JUnit artifact for that run recorded tests=15174 failures=0 errors=0, with all three new tests passing.

@aminghadersohi

Copy link
Copy Markdown
Contributor

Rechecked edb7e9f: SQL-expression save-mode reporting and saved/transient Bubble renderer dispatch still work; 43 targeted tests pass and current required CI is green. The new sort precedence introduces one public-path regression:

For native Bubble form-data with orderby=[size], order_desc=False, the preview strategies and saved-data fallback pass hardcoded order_desc=True, not a user-requested override. The changed helper now lets that override the saved chart.

Captured query dictionaries with DB execution mocked:

  • Compile/cached-data path: orderby=[(size, True)] — ascending, matching Explore.
  • Saved/transient preview and saved-data fallback: orderby=[(size, False)] — descending.
  • Running the previous helper with the same fallback arguments gives ascending.

With row_limit=1 on the saved-data fallback, this selects the largest bubble instead of the requested smallest; it changes the selected data, not just display ordering.

Keeping explicit-argument precedence is reasonable, but please update these callers to forward the chart's saved direction (or omit the override for Bubble). Add a regression through the preview strategy and saved-data fallback with order_desc=False; the new helper-only test currently verifies the override without checking whether callers meant to override the chart.

No contributor code changed; these were isolated source/unit-harness checks, not a live database/browser run.

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #157548

Actionable Suggestions - 0
Review Details
  • Files reviewed - 4 · Commit Range: b1b9edb..edb7e9f
    • superset/mcp_service/chart/chart_helpers.py
    • superset/mcp_service/chart/preview_utils.py
    • tests/unit_tests/mcp_service/chart/test_bubble_chart.py
    • tests/unit_tests/mcp_service/chart/tool/test_generate_chart.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

@gkneighb

Copy link
Copy Markdown
Contributor Author

@aminghadersohi You're right, and the regression is mine — thanks for catching it before it merged. Fixed at a75b6ccd52.

The defect was in the callers, and your framing ("not a user-requested override") is exactly it. Four sites passed a hardcoded order_desc=True into the query builder:

  • get_chart_preview.py:272 (ASCII), :352 (table), :454 (Vega-Lite)
  • get_chart_data.py:616 (saved-data fallback)

Once the argument began outranking form_data, that literal True started overriding the chart's own flag. All four now forward the chart's direction:

order_desc=form_data.get("order_desc", True),

What convinced me this is the right shape rather than special-casing bubble: the same module already did it this way everywhere else. get_chart_data.py:560 (cached form_data) and :1067 (unsaved form_data) were already forwarding form_data.get("order_desc", True) — which is precisely why your probe found the compile/cached path ascending and the saved/preview path descending. The four sites I changed were the outliers, so the split you measured is now closed in the direction the rest of the module already went.

Regressions through both public paths, as you asked, rather than only the helper:

  • test_saved_chart_preview_forwards_its_own_sort_direction — drives VegaLitePreviewStrategy.generate() on a saved bubble chart with order_desc: False, row_limit: 1, and asserts the direction reaching build_query_context_from_form_data is False.
  • TestSavedDataFallbackSortDirection::test_fallback_forwards_the_charts_saved_direction — drives get_chart_data through the tool with a chart that has no query_context (so it takes the fallback) and asserts the same.
  • test_no_explicit_direction_defers_to_the_saved_flag — the builder contract the callers now rely on: no explicit argument means the saved flag stands.

The existing override test stays, since explicit-argument precedence is still the rule — it just no longer has a caller asserting a direction it never knew.

One caveat on my own verification, same as last round: this environment cannot execute the two tool-level test files (app-init conftest fails on an outdated SQLAlchemy/Flask, and --noconftest trips duplicate model registration), so those two tests are CI-arbitrated. Locally verified: the builder contract test, the full bubble file (39 passing), and a diff of the whole mcp_service suite against a clean master worktree showing no new failures. Last round's equivalents did pass in CI, and I'll watch this run.

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 15, 2026
@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #d95721

Actionable Suggestions - 0
Additional Suggestions - 2
  • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py - 1
    • Mock bypasses fallback path · Line 2947-2947
      `QueryContextFactory.create` returns a bare `object()`, but the tool then calls `set_query_context_form_data(query_context, ...)` (get_chart_data.py:701), which reads `query_context.form_data`/`.queries` and raises `AttributeError`, swallowed by the broad `except` (1000-1008). The test passes only because `recording_builder` sets `captured["order_desc"]` before that failure. Return `SimpleNamespace(form_data={}, queries=[])` so the fallback path is actually exercised.
  • tests/unit_tests/mcp_service/chart/test_bubble_chart.py - 1
    • Redundant test duplication · Line 321-337
      This test duplicates `test_order_desc_false_sorts_ascending`: both set `form_data['orderby']=size` and `order_desc=False`, call `build_query_dicts_from_form_data` without an explicit `order_desc` param, and assert `[(size, True)]`. The name 'defers_to_the_saved_flag' is also misleading since the flag is set explicitly. Consider removing it or covering the no-flag default instead.
Review Details
  • Files reviewed - 5 · Commit Range: edb7e9f..a75b6cc
    • superset/mcp_service/chart/tool/get_chart_data.py
    • superset/mcp_service/chart/tool/get_chart_preview.py
    • tests/unit_tests/mcp_service/chart/test_bubble_chart.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_preview.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

@gabotorresruiz

Copy link
Copy Markdown
Contributor

Hey Greg, I re-verified everything at a75b6ccd in a clean worktree with a venv built from this branch's own requirements. Every claim below is from execution, not reading.

All previously blocking items check out:

  • Scalar y through the shared analyzers: driving analyze_chart_semantics and analyze_chart_capabilities directly with a bubble config no longer raises, and the full bubble file passes (41 tests).
  • SQL-expression x: with x={"sql_expression": "AVG(gdp)", "label": "GDP"} the story reads This bubble_v2 chart analyzes GDP, life_expectancy, no None; the symmetric y case is clean too.
  • Saved-chart Vega-Lite preview: VegaLitePreviewStrategy.generate() on a saved bubble chart now returns a circle mark with x=AVG(gdp), y=AVG(life_expectancy), size=SUM(population), color=continent instead of the generic fallback.
  • Sort direction: all four callers forward form_data.get("order_desc", True), and I swept superset/mcp_service/ for any remaining hardcoded order_desc=True; there are none. I also ran your three new tests against edb7e9ff: test_saved_chart_preview_forwards_its_own_sort_direction and test_fallback_forwards_the_charts_saved_direction fail there exactly as they should, so they genuinely pin the fix.

Since your environment could not run the tool-level files, I ran them here: test_get_chart_preview.py plus test_get_chart_data.py 200 passed, test_generate_chart.py 33 passed, and the whole tests/unit_tests/mcp_service/chart tree 1635 passed, 1 skipped.

The only thing keeping me from approving is mechanical: the branch is in conflict with master (#44004 touched test_get_chart_data.py; only that test file conflicts, the source files auto-merge cleanly), and because of that GitHub has not started the required CI on this head at all. One note for the rebase: #44004 renamed chart to chart_facts in the saved-data fallback but kept the hardcoded order_desc=True there, so your fix survives the merge and is still needed. Once you rebase and CI comes back green I will lift my request for changes; nothing further needed on the code itself from my side.

I am deliberately not repeating the two nits the bot raised on this head (the duplicated ordering test and the shallow object() mock in the fallback test); neither is blocking, take them or leave them.

@gkneighb
gkneighb force-pushed the feat/mcp-bubble-plugin branch from a75b6cc to ed8662c Compare September 16, 2026 02:49
@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Sep 16, 2026
@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #ba2b1b

Actionable Suggestions - 0
Additional Suggestions - 4
  • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py - 1
    • Test mock raises AttributeError · Line 3276-3276
      `QueryContextFactory.create` returns a plain `object()`, but the fallback path calls `set_query_context_form_data(query_context, ...)` (get_chart_data.py:780), which reads `query_context.form_data` and `query_context.queries`. A plain `object()` has neither, so this test raises `AttributeError` before reaching the `assert captured["order_desc"] is False`. Return `SimpleNamespace(queries=[], form_data={})` as done at line 1972.
  • superset/mcp_service/chart/chart_utils.py - 2
    • Metric label precedence mismatch · Line 1842-1843
      `_bubble_chart_what` uses label-first precedence (`label or name or sql_expression`) while `analyze_chart_semantics` (lines 2070/2074) uses name-first (`name or label or sql_expression`) for the same metric fallback. When a column has both a name and a label, the generated chart name and the data story will name the same metric differently. Align both to one precedence.
    • Avoid Any type annotation · Line 1953-1953
      `Any` is disallowed in type annotations. Use a more specific type like `ColumnRef | list[ColumnRef] | None` for the `value` parameter and `list[ColumnRef]` for the return type.
  • superset/mcp_service/chart/plugins/bubble.py - 1
    • Disallow dynamic typing in config · Line 81-81
      Replace `Any` with a more specific type or add `# noqa: ANN401` to suppress the warning. This occurs in multiple methods: `extract_column_refs`, `to_form_data`, `generate_name`, `resolve_viz_type`, and `normalize_column_refs`. This patch adds a noqa comment to `extract_column_refs`.
Review Details
  • Files reviewed - 15 · Commit Range: 09fc8db..ed8662c
    • superset/mcp_service/app.py
    • superset/mcp_service/chart/chart_helpers.py
    • superset/mcp_service/chart/chart_utils.py
    • superset/mcp_service/chart/plugins/__init__.py
    • superset/mcp_service/chart/plugins/bubble.py
    • superset/mcp_service/chart/preview_utils.py
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/tool/generate_chart.py
    • superset/mcp_service/chart/tool/get_chart_data.py
    • superset/mcp_service/chart/tool/get_chart_preview.py
    • superset/mcp_service/chart/tool/get_chart_type_schema.py
    • tests/unit_tests/mcp_service/chart/test_bubble_chart.py
    • tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_preview.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

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 16, 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.

Both items from my last review are fixed. I verified them by execution against ed8662c5, not by reading: I booted a real Superset app on a scratch metadata DB with a real dataset and drove the actual MCP tools.

Scalar y crashing the shared analyzers (the blocking one): generate_chart with save_chart=True returns the saved chart (id=2, viz_type=bubble_v2). At my previous review SHA the same config still raises TypeError: object of type 'ColumnRef' has no len() in analyze_chart_capabilities and AttributeError: 'tuple' object has no attribute 'name' in analyze_chart_semantics, so _as_column_list() is carrying exactly that weight and TestBubbleChartAnalyzers pins it. The sql_expression variant saves too, with the story reading This bubble_v2 chart analyzes GDP per capita, life_expectancy.

LLM-facing enumerations (not a blocker): all of them are covered now, generate_chart.py:89,135,162 and app.py:419,431.

The rest of this round holds on real SQL rather than mocks:

  • get_chart_data on the saved chart, which has no query_context, returns country, continent, AVG(gdp), AVG(life_expectancy), SUM(population).
  • With orderby=[size] and row_limit=1, order_desc=False gives me Peru (smallest population) and order_desc=True gives Brazil (largest). That is the caller regression from the last round, closed.
  • The saved chart Vega-Lite preview reaches the bubble renderer: mark: circle, x=AVG(gdp), y=AVG(life_expectancy), size=SUM(population).
  • x: {"name": "country"} on a TEXT column is rejected up front with invalid_aggregation, and an unknown entity returns column_not_found with suggestions.

Locally: 41 tests in test_bubble_chart.py, and 4071 in tests/unit_tests/mcp_service with 2 failures in test_query_dataset.py that reproduce identically at the merge base, so they are not yours.

LGTM.

Heads up on the rebase you already need: the Gantt plugin landed on master and conflicts with this branch in app.py, chart/schemas.py, chart/plugins/__init__.py, chart/tool/generate_chart.py, get_chart_preview.py and get_chart_type_schema.py, all in the shared enumerations, so it should be mechanical.

Not a change request, just so it is not lost: #44188 switches every plugin's normalize_column_refs to config.model_dump(exclude_unset=True) so merge_chart_form_data can keep an omitted color_scheme or row_limit. Bubble is not on its list, for the obvious reason. I merged the two branches locally and an update_chart that omits both resets bubble to supersetColors and 10000 while pie keeps googleCategory10c and 25. Whichever of you lands second needs that one word in plugins/bubble.py:106.

Greg Neighbors and others added 4 commits September 18, 2026 08:51
Adds chart_type="bubble_v2" to generate_chart: an entity dimension plus
separate x, y and size metrics and an optional series dimension, matching
the frontend Bubble buildQuery contract.

Bubble is the first config in the union whose `y` is a single column rather
than a list, so the shared analyzers are taught to accept either shape —
`analyze_chart_capabilities` raised TypeError on len(config.y) and
`analyze_chart_semantics` iterated the model into (field, value) tuples,
crashing generate_chart after the chart row had already been created.

Three further gaps found in review:

- x, y and size are metric slots, so a bare column is summed. That default
  was applied in create_metric_object, where the ref still reported
  is_metric False and the aggregate-compatibility check skipped it: SUM of
  a text column reached the database while spelling out the same SUM was
  rejected. The config now records the implicit aggregate.

- Bubble's buildQuery pairs form_data['orderby'] with the negated
  order_desc flag. The MCP path builds query dicts directly, so a saved
  chart's "Sort query by" metric was dropped and row_limit truncated an
  unordered result.

- The Vega-Lite preview read x_axis/metrics/groupby, none of which bubble
  form_data carries, and fell back to a bar mark with no encoding. Bubble
  now gets a circle mark with x/y/size and a series (or entity) color.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WaKNuh9jhZHs2zxLuPLRKd
Two follow-ups from review of the bubble plugin.

A SQL-expression ColumnRef has no name, and `analyze_chart_semantics`
appended `config.x.name` unguarded before joining the result, so a valid
`x={"sql_expression": ..., "label": ...}` raised TypeError while the
response was being assembled — in save mode after the create command had
already committed the chart. The `y` side already fell back to the label or
the expression; `x` now does too, and the case is covered through
generate_chart as well as at the analyzer.

`VegaLitePreviewStrategy` special-cased only gauge before falling through
to its generic spec builder, which reads positions off the first result
columns it finds: a saved bubble chart was drawn with x=entity, y=series
and no size or color. Saved and cached previews now route through the
bubble renderer, after the no-data guard so an empty result still reports
NoDataError.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WaKNuh9jhZHs2zxLuPLRKd
Two defects found by review of the previous commit.

`_build_single_query_dict` read the sort direction from form_data while
ignoring its own `order_desc` argument, so a caller passing the flag
explicitly — get_chart_data does — produced a query whose `order_desc` and
`orderby` disagreed. The argument now wins, falling back to form_data.

The bubble preview resolved its metric column names with a local helper
that only understood an explicit label, while `metric_result_label` was
already imported in the same module and reconstructs `AVG(col)` from a
SIMPLE metric and resolves SQL-expression metrics. A saved chart whose
form_data carries unlabeled metrics silently lost those channels from the
spec. The local copy is gone.

The generation regression test now asserts the data story the semantics
analyzer produces, rather than only that the chart was reported.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WaKNuh9jhZHs2zxLuPLRKd
Three preview strategies and the saved-data fallback passed a hardcoded
order_desc=True into the query builder. Once an explicit argument began
outranking form_data, that hardcoded value overrode the chart's own flag:
a saved bubble chart sorted ascending came back descending, and with a row
limit that returns the largest rows where the smallest were requested — a
change in which data is selected, not just how it is ordered.

All four now forward form_data's own direction, matching what the cached
and unsaved paths in get_chart_data already did.

Regressions cover both public paths — the preview strategy and the
saved-data fallback each assert the chart's order_desc=False is forwarded
— plus the builder contract that an omitted direction defers to form_data.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WaKNuh9jhZHs2zxLuPLRKd
@gkneighb
gkneighb force-pushed the feat/mcp-bubble-plugin branch from ed8662c to c825e07 Compare September 18, 2026 12:54
@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Sep 18, 2026

@bito-code-review bito-code-review Bot 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.

Code Review Agent Run #b7102a

Actionable Suggestions - 4
  • tests/unit_tests/mcp_service/chart/test_bubble_chart.py - 3
  • tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py - 1
Additional Suggestions - 8
  • superset/mcp_service/chart/preview_utils.py - 1
    • Always-true tooltip guard · Line 1243-1244
      Inside `if encoding:`, the `if tooltip:` guard is always true: `tooltip` is built at lines 1229-1231 from `encoding.values()` and `encoding` gains no keys until line 1244, so the two are always the same length. The nested branch reads as if tooltip could be empty here; flattening the block removes the dead condition.
  • superset/mcp_service/chart/chart_helpers.py - 2
    • Duplicated bubble viz-type pair · Line 485-485
      Lines 485 and 681 both encode the bubble viz-type pair as literals. Adding a future bubble variant to one but not the other would silently split metric resolution from sort-metric handling. Define a shared module constant (e.g. `_BUBBLE_VIZ_TYPES`) next to `_SORT_METRIC_VIZ_TYPES` and use it in `resolve_metrics` and the frozenset, matching the existing `_DECK_TIMESERIES_VIZ_TYPES` pattern.
    • Inconsistent viz_type fallback · Line 686-686
      `resolve_sort_metric` re-derives `viz_type` from `form_data` only, while `resolve_metrics` receives the fallback-resolved value from `build_query_dicts_from_form_data` (form_data, then `chart.viz_type`). If form_data lacks `viz_type` but the chart row is a bubble type, metrics resolve via x/y/size yet the sort metric is silently dropped. Consider threading the resolved `viz_type` through.
  • tests/unit_tests/mcp_service/chart/test_bubble_chart.py - 3
    • Missing return type hint · Line 286-287
      New helper `_size_metric` lacks an explicit return type annotation. Repo rules (BITO.md adaptive rules 7819/12490) require return type hints on all new test helpers, and the sibling `_query` helper has the same gap. Annotate as `-> dict[str, Any]` so mypy covers what `map_bubble_config` returns.
    • Missing helper type hints · Line 290-291
      Helper `_query` lacks a return type annotation (and `monkeypatch`/`**overrides` parameter types), unlike the test methods in this class which annotate `-> None`. BITO.md rules 7819/12490 require full annotations on new test helpers; annotate `-> dict[str, Any]` and type `monkeypatch: pytest.MonkeyPatch`.
    • Test under-asserts y classification · Line 196-202
      This test's name and the class docstring promise single-column-y classification, but `analyze_chart_capabilities` dedupes `data_types` via `list(set(...))` (chart_utils.py:2316) and bubble's x is always a metric too, so the assertion passes even if the y branch is dropped. Rename the test to match what it pins (crash-freedom) or assert y's contribution via a discriminating observable.
  • tests/unit_tests/mcp_service/chart/tool/test_get_chart_preview.py - 1
    • Test fixture weakens sort-direction path · Line 142-154
      This test sets `orderby` in form_data, so `_build_single_query_dict` (`chart_helpers.py:704`) copies it verbatim and the `elif resolve_sort_metric(...)` branch at `chart_helpers.py:719` never runs — the negated-direction `orderby` the docstring describes is not exercised. The `order_desc` kwarg assertion still holds (it is forwarded from `get_chart_preview.py:474`), but the direction contract is only half-pinned. Drop `orderby` from these params or also assert the built `orderby`.
  • superset/mcp_service/chart/plugins/bubble.py - 1
    • Replace Any with specific types · Line 81-81
      Replace `Any` with specific types in method signatures: `config` should be `BubbleChartConfig`, `dataset_context` should be a concrete type, and return types should be explicit. This addresses ANN401 for all occurrences.
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 - 15 · Commit Range: 4316cf1..c825e07
    • superset/mcp_service/app.py
    • superset/mcp_service/chart/chart_helpers.py
    • superset/mcp_service/chart/chart_utils.py
    • superset/mcp_service/chart/plugins/__init__.py
    • superset/mcp_service/chart/plugins/bubble.py
    • superset/mcp_service/chart/preview_utils.py
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/tool/generate_chart.py
    • superset/mcp_service/chart/tool/get_chart_data.py
    • superset/mcp_service/chart/tool/get_chart_preview.py
    • superset/mcp_service/chart/tool/get_chart_type_schema.py
    • tests/unit_tests/mcp_service/chart/test_bubble_chart.py
    • tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_preview.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

Comment on lines +33 to +34
def _base(**overrides):
cfg = {

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.

Missing type hints on helper

The _base helper used by every test in this file has no parameter/return annotations and no docstring, while the sibling helper _config in tests/unit_tests/mcp_service/chart/test_gantt_chart.py is fully annotated. BITO.md rules 7819/12490 mandate explicit type hints and docstrings on new test helpers. Annotate it and add a short docstring.

Code Review Run #b7102a


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

)
form_data = map_bubble_config(config)
assert form_data["series"] == "continent"
assert form_data["adhoc_filters"], "filters must map to adhoc_filters"

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.

Weak filter assertion

This only checks adhoc_filters is non-empty; _add_adhoc_filters builds a specific {clause, expressionType, subject, operator, comparator} dict from config.filters, and none of that mapping is verified. A regression in map_filter_operator or the subject mapping would still pass. Assert the full filter dict.

Code Review Run #b7102a


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

"""

def test_bubble_v2_metrics_resolved(self) -> None:
from superset.mcp_service.chart.chart_helpers import resolve_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.

Function-local imports

These tests import resolve_metrics inside the function body; the same pattern repeats at lines 150, 157 and 162 for registry and display_name_for_viz_type. No circular dependency justifies it — the module already imports map_bubble_config from the same package at top level. Move these imports to module level.

Code Review Run #b7102a


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

"""

@pytest.mark.asyncio
async def test_saved_bubble_with_sql_expression_x_is_reported(self) -> None:

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.

Missing Test Docstring

New test methods in this file carry their own docstrings (e.g. test_detached_chart_is_reported_as_created), and BITO rule 12148 requires a docstring on every newly added test function. test_saved_bubble_with_sql_expression_x_is_reported relies only on the class docstring. Add a one-line method docstring describing the scenario (SQL-expression x metric survives the semantics analyzer in save mode).

Code Review Run #b7102a


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

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

Rebase looks clean, and I checked it rather than trusting the conflict resolution.

git range-diff against my last approval ed8662c5 marks commits 3 and 4 identical and shows 1 and 2 differing only in context. Comparing every line this PR adds on both sides, the only deltas are three docstring lines that absorbed gantt while keeping bubble_v2, for instance app.py:435 now reading histogram, box_plot, waterfall, gantt, bubble_v2, and interactive_pivot. Nothing bubble was dropped, and both types are present at every enumeration: app.py:423,435, generate_chart.py:89,135,167, get_chart_type_schema.py:77,213,349, plugins/__init__.py:32,57,71 and the ChartConfig union.

The part I wanted to see was chart_helpers.py, since the Gantt plugin changed the branch your elif hangs off. Master now sets qd["orderby"] = form_data["orderby"] at :704 and gates the sort_by_metric branch with and not qd.get("orderby") at :717, so bubble form_data falls through to your elif at :719 and replaces the raw value with the tuple form. Same query as before the rebase, confirmed live on a real dataset: orderby=[size] with row_limit=1 returns Peru at order_desc=False and Brazil at order_desc=True, and the saved chart preview still comes back mark: circle with x=AVG(gdp), y=AVG(life_expectancy), size=SUM(population).

Locally at this head: 41 in test_bubble_chart.py, 1906 in tests/unit_tests/mcp_service/chart, and 4509 across tests/unit_tests/mcp_service with zero failures.

LGTM.

Nothing for you to do on my earlier note: #44188 is still open and its plugin list predates both gantt.py and bubble.py, so the exclude_unset=True sweep is for its rebase to pick up, not yours.

@rusackas rusackas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Heya @gkneighb, this looks solid. Traced the orderby fix against the actual frontend buildQuery chain (dndSortByControl through Bubble/buildQuery.ts's orderby[0] unwrap) and the aggregate-validation fix against DatasetValidator._validate_aggregations, both hold up. Also confirmed @gabotorresruiz's two review concerns, the y-as-single-column crash in the shared analyzers and the missing bubble_v2 entries in the LLM-facing docstrings, got fixed in the code even though the threads never got clicked resolved.

Nice catches on the shared-analyzer bugs along the way, especially the orphaned-chart-on-crash one. Approving.

@rusackas
rusackas merged commit 5a2a90b into apache:master Sep 21, 2026
76 checks passed
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

change:backend Requires changing the backend size/XXL viz:charts:bubble Related to the Bubble chart

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants