Skip to content

fix(mcp): apply extra_form_data filters when rendering chart SQL - #43478

Open
aminghadersohi wants to merge 10 commits into
apache:masterfrom
aminghadersohi:aminghadersohi/fix-get-chart-sql-extra-form-data
Open

fix(mcp): apply extra_form_data filters when rendering chart SQL#43478
aminghadersohi wants to merge 10 commits into
apache:masterfrom
aminghadersohi:aminghadersohi/fix-get-chart-sql-extra-form-data

Conversation

@aminghadersohi

Copy link
Copy Markdown
Contributor

Recreates #43338, which GitHub auto-closed when its head fork was deleted. Same commits, no content changes.


SUMMARY

get_chart_sql's request schema had no extra_form_data field. Pydantic silently
drops unrecognized fields by default, so any filters passed alongside a chart
identifier were dropped before validation ever ran — the tool always rendered the
chart's unfiltered baseline SQL regardless of what was passed in.

get_chart_data already merges extra_form_data correctly via
merge_extra_form_data_filters_into_query / build_query_context_from_form_data
(added in a prior fix). This PR adds the same extra_form_data field to
GetChartSqlRequest and wires it into both of get_chart_sql's SQL-construction
paths (saved query_context, and the form_data fallback), reusing the existing
merge helpers instead of adding new filter-merging logic.

get_chart_data already applied filters correctly. The shared helper update in this
PR additionally preserves normalized relative-time extras (relative_start and
relative_end) for both chart-data and chart-SQL query construction.

TESTING INSTRUCTIONS

  • New unit tests in tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py:
    • GetChartSqlRequest accepts and stores extra_form_data (previously silently
      dropped).
    • _build_query_context_from_form_data forwards extra_form_data to the query
      factory.
    • _sql_from_saved_query_context merges extra_form_data into the query handed
      to ChartDataQueryContextSchema.load before rendering SQL.
    • End-to-end: request.extra_form_data reaches the saved-query_context SQL
      builder and shows up in the rendered SQL.
  • New unit tests in tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
    cover the (already-correct, previously untested) get_chart_data path where a
    chart identifier + extra_form_data are both provided — both the filters and
    adhoc_filters extra_form_data formats, plus a TEMPORAL_RANGE filter.
  • pytest tests/unit_tests/mcp_service/ — full suite passes.
  • pre-commit run on all changed files — clean.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

get_chart_sql had no extra_form_data field on its request schema, so
any filters passed alongside a chart identifier were silently dropped
before validation and the tool always rendered the chart's unfiltered
baseline SQL. get_chart_data already merges extra_form_data correctly;
this wires the same merge helpers into get_chart_sql's saved
query_context and form_data fallback paths.
Adds coverage for the form_data_key-only path, closing a patch-coverage
gap flagged on the extra_form_data fix.
Address PR review feedback: an extra_form_data filter entry missing a
required key (e.g. "op") raised an unhandled KeyError out of
get_chart_sql instead of a structured ChartError. Also use a keyword
argument for extra_form_data at the _sql_from_form_data call site for
clarity, and strengthen the saved-query_context regression tests to
actually exercise both the "filters" and "adhoc_filters" extra_form_data
formats (previously only "filters" was tested despite the docstring
claiming both).
@dosubot dosubot Bot added api Related to the REST API change:backend Requires changing the backend labels Aug 24, 2026
@bito-code-review

bito-code-review Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Code Review Agent Run #b67a05

Actionable Suggestions - 0
Additional Suggestions - 1
  • superset/mcp_service/chart/tool/get_chart_sql.py - 1
    • Test gap: invalid extra_form_data · Line 178-191
      The invalid `extra_form_data` error path (lines 178-191) lacks test coverage. Add a test that passes malformed extra_form_data to `_sql_from_saved_query_context` and asserts it returns `ChartError(error_type='ValidationError')`.
Review Details
  • Files reviewed - 6 · Commit Range: 09e60b9..a642de1
    • superset/mcp_service/chart/chart_helpers.py
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/tool/get_chart_sql.py
    • tests/unit_tests/mcp_service/chart/test_chart_helpers.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.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 evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

@github-actions github-actions Bot removed the api Related to the REST API label Aug 24, 2026
@netlify

netlify Bot commented Aug 24, 2026

Copy link
Copy Markdown

Deploy Preview for superset-docs-preview ready!

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

Comment on lines +1515 to +1516
assert data["error_type"] == "ValidationError"
assert "Invalid chart query data" in data["error"]

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.

Suggestion: The assertion expects the fallback-path message, but malformed filters on the saved query_context path are caught earlier and return an error beginning with Invalid extra_form_data filter, so this test will fail even when the production error handling behaves as implemented. Assert the actual saved-context validation message or change the production path if the fallback message is intended. [logic error]

Severity Level: Major ⚠️
- ❌ The new malformed-filter regression test fails during the chart SQL test suite.
- ⚠️ CI cannot pass until the expected error message matches the saved-context path.

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py
**Line:** 1515:1516
**Comment:**
	*Logic Error: The assertion expects the fallback-path message, but malformed filters on the saved `query_context` path are caught earlier and return an error beginning with `Invalid extra_form_data filter`, so this test will fail even when the production error handling behaves as implemented. Assert the actual saved-context validation message or change the production path if the fallback message is intended.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment thread superset/mcp_service/chart/tool/get_chart_sql.py
@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged issue is correct. In _sql_from_saved_query_context, the try-except block catches errors during the merging of extra_form_data and returns an error message starting with Invalid extra_form_data filter. However, the test test_malformed_extra_form_data_filter_returns_clean_error asserts that the error message contains Invalid chart query data, which is the message returned by the fallback path (_sql_from_form_data), not the saved-context path. To resolve this, update the test assertion to expect Invalid extra_form_data filter when testing the saved-context path, or adjust the production code if the fallback message is intended.

tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py

data = result.structured_content.get("result", result.structured_content)
            assert data["error_type"] == "ValidationError"
            assert "Invalid extra_form_data filter" in data["error"]

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

LGTM

Filter merging on the saved query_context path needs the context's
datasource id/type. Resolving those inside the same try as the merge
meant a stale context (missing or malformed "datasource") was reported
as "Invalid extra_form_data filter", skipping the form_data fallback so
charts with valid params failed instead of rendering.

Resolve the datasource up front and return None on failure so the caller
rebuilds from form_data; keep the ValidationError for merge failures,
which really are bad request filters.

Also fixes the malformed-filter regression test, which still asserted
the fallback path's "Invalid chart query data" message after the
saved-context error branch was added.

Co-Authored-By: Claude <noreply@anthropic.com>
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Thanks — both flagged issues were accurate, confirmed by reproducing them locally. Fixed in dfedf65.

1. Test asserted the wrong error message (codeant + bito). Confirmed real; the test failed:

assert 'Invalid chart query data' in "Invalid extra_form_data filter: 'op'"

The malformed-filter regression test was written against the fallback path's message, but a later commit in this branch added the saved-context error branch, which reports the malformed filter directly. Updated the assertion to expect Invalid extra_form_data filter — the more precise message is the correct behavior here.

2. ChartError bypasses the form_data fallback (codeant). The underlying problem is real, though the suggested fix would trade one bug for another. qc_json["datasource"]["id"] sat inside the same try as the merge, so both causes collapsed into one error:

  • a stale saved context (missing/malformed datasource) → should fall back to form_data
  • malformed request filters → should surface a ValidationError

Returning None for everything, as suggested, would fix the stale case but silently swallow bad user filters at this path. Instead the datasource is now resolved up front — failure there returns None so the caller rebuilds from form_data — and the merge keeps its ValidationError. Both cases now behave correctly.

3. Test gap on the invalid-extra_form_data path (bito). That path was already covered end-to-end by test_malformed_extra_form_data_filter_returns_clean_error. Added test_stale_query_context_falls_back_instead_of_erroring to cover the newly separated stale-context branch, which was the genuinely untested one.

pytest tests/unit_tests/mcp_service/ — 3514 passed. pre-commit run — clean.

@codecov

codecov Bot commented Aug 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.94737% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.84%. Comparing base (a05a099) to head (dfedf65).
⚠️ Report is 50 commits behind head on master.

Files with missing lines Patch % Lines
superset/mcp_service/chart/tool/get_chart_sql.py 75.75% 7 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #43478       +/-   ##
===========================================
+ Coverage   66.81%   78.84%   +12.02%     
===========================================
  Files        2876     2877        +1     
  Lines      164237   164786      +549     
  Branches    37917    38001       +84     
===========================================
+ Hits       109743   129919    +20176     
+ Misses      52310    32416    -19894     
- Partials     2184     2451      +267     
Flag Coverage Δ
hive 38.01% <7.89%> (-0.09%) ⬇️
mysql 57.75% <7.89%> (-0.04%) ⬇️
postgres 57.77% <7.89%> (-0.05%) ⬇️
presto 39.93% <7.89%> (-0.10%) ⬇️
python 83.64% <78.94%> (+24.38%) ⬆️
sqlite 57.46% <7.89%> (-0.05%) ⬇️
unit 73.70% <78.94%> (-26.30%) ⬇️

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.

@bito-code-review

bito-code-review Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Code Review Agent Run #b18805

Actionable Suggestions - 0
Review Details
  • Files reviewed - 2 · Commit Range: a642de1..dfedf65
    • superset/mcp_service/chart/tool/get_chart_sql.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.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 evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

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/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants