Repository navigation
feat(mcp): bubble chart type plugin - #43572
Conversation
Codecov Report❌ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
a76d61c to
f89b3b0
Compare
|
The review comment is correct. The 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 selfWould 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 |
There was a problem hiding this comment.
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
aminghadersohi
left a comment
There was a problem hiding this comment.
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; headf89b3b00.- 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.
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
aminghadersohi
left a comment
There was a problem hiding this comment.
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.
Code Review Agent Run #5f1a23Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
6466305 to
30ef2c8
Compare
There was a problem hiding this comment.
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.
|
sorry i accidentally pushed to your pr. will undo that commit shortly. thank you for your work |
|
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. |
Code Review Agent Run #ca8d39Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
gabotorresruiz
left a comment
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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, | |||
There was a problem hiding this comment.
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.
Code Review Agent Run #ce458aActionable Suggestions - 0Additional Suggestions - 4
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
|
New head Sort direction ignored the caller's flag ( Unlabeled metrics were dropped from the bubble preview ( Test strengthened. The fourth suggestion — that the 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 |
|
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 Captured query dictionaries with DB execution mocked:
With 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 No contributor code changed; these were isolated source/unit-harness checks, not a live database/browser run. |
Code Review Agent Run #157548Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
|
@aminghadersohi You're right, and the regression is mine — thanks for catching it before it merged. Fixed at The defect was in the callers, and your framing ("not a user-requested override") is exactly it. Four sites passed a hardcoded
Once the argument began outranking form_data, that literal 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. Regressions through both public paths, as you asked, rather than only the helper:
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 |
Code Review Agent Run #d95721Actionable Suggestions - 0Additional Suggestions - 2
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
|
Hey Greg, I re-verified everything at All previously blocking items check out:
Since your environment could not run the tool-level files, I ran them here: The only thing keeping me from approving is mechanical: the branch is in conflict with master (#44004 touched I am deliberately not repeating the two nits the bot raised on this head (the duplicated ordering test and the shallow |
a75b6cc to
ed8662c
Compare
Code Review Agent Run #ba2b1bActionable Suggestions - 0Additional Suggestions - 4
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
gabotorresruiz
left a comment
There was a problem hiding this comment.
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_dataon the saved chart, which has noquery_context, returnscountry, continent, AVG(gdp), AVG(life_expectancy), SUM(population).- With
orderby=[size]androw_limit=1,order_desc=Falsegives me Peru (smallest population) andorder_desc=Truegives 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 withinvalid_aggregation, and an unknownentityreturnscolumn_not_foundwith 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.
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
ed8662c to
c825e07
Compare
There was a problem hiding this comment.
Code Review Agent Run #b7102a
Actionable Suggestions - 4
-
tests/unit_tests/mcp_service/chart/test_bubble_chart.py - 3
- Missing type hints on helper · Line 33-34
- Weak filter assertion · Line 121-121
- Function-local imports · Line 138-138
-
tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py - 1
- Missing Test Docstring · Line 992-992
Additional Suggestions - 8
-
superset/mcp_service/chart/preview_utils.py - 1
-
Always-true tooltip guard · Line 1243-1244Inside `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-485Lines 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-287New 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-291Helper `_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-202This 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-154This 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-81Replace `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
- Duplicate bubble viz-type constant · Line 1196-1196
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
| def _base(**overrides): | ||
| cfg = { |
There was a problem hiding this comment.
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" |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
SUMMARY
Adds a
generate_chartMCP plugin for the bubble chart type (viz_type: bubble_v2), so the MCPgenerate_charttool 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
buildQuerycontract: anentitydimension identifies each bubble, three separate metrics position and size it (xhorizontal,yvertical,sizearea), and an optionalseriesdimension colours the bubbles by group.Follows the established plugin pattern (
pie/funnel/gauge/treemap/heatmap/radar/waterfall) — a config schema, amap_*_configmapper, a plugin class, and registration:BubbleChartConfig—entity,x,y, andsizerequired; optionalseries,row_limit(default 10000),filters,color_scheme. Added to theChartConfigdiscriminated union and theget_chart_type_schemaadapters.x/y/sizeare three separate metric keys (the query layer aliases them intometrics), not a metrics array;entity/seriesmay not besaved_metric/sql_expression(dimensions, not metrics).map_bubble_config— maps the config toform_data; saved metrics pass through as bare name strings, ad-hoc metrics as SIMPLE/SQL adhoc objects.seriesis omitted fromform_datawhen unset.BubbleChartPlugin— registered in the plugin registry. Only the legacybubblekey was in the recommendation category map, so this addsbubble_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:
y. Bubble is the first config in the union whoseyis a single column, soanalyze_chart_capabilitiesraisedTypeError: object of type 'ColumnRef' has no len()andanalyze_chart_semanticsiterated the model into(field, value)tuples.generate_chartcalls both unguarded, and withsave_chart=Truethe chart row is created before the crash — so the user got an orphaned chart and no URL. Both sites now accept either shape.create_metric_objectdefaults a bare column toSUM, but the ref reportedis_metricFalse, so the aggregate-compatibility check skipped it:x={"name": "country"}on a VARCHAR column sentSUM(country)to the database while spelling out that sameSUMwas rejected up front. The config now records the default, which routes it through the existing check.buildQuerypairsform_data['orderby']with the negatedorder_descflag (default descending). The MCP path builds query dicts directly and never read it, sorow_limittruncated an unordered result — arow_limit=1chart showed an arbitrary bubble rather than the largest.x_axis/metrics/groupby, none of which bubble form_data carries, so the advertised preview fell back to abarmark with noencodingat 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/seriesnot-a-metric, saved-metric axis accepted, extra-field rejection),ChartConfigunion dispatch,form_datamapping (three separate metric keys,seriesomitted 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_chartMCP 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
🤖 Generated with Claude Code