Skip to content

fix(mcp): honor and validate chart filters - #43478

Merged
rusackas merged 11 commits into
apache:masterfrom
aminghadersohi:aminghadersohi/fix-get-chart-sql-extra-form-data
Aug 26, 2026
Merged

fix(mcp): honor and validate chart filters#43478
rusackas merged 11 commits into
apache:masterfrom
aminghadersohi:aminghadersohi/fix-get-chart-sql-extra-form-data

Conversation

@aminghadersohi

@aminghadersohi aminghadersohi commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Recreates #43338, which GitHub auto-closed when its head fork was deleted. This version also rejects request filters that reference unknown dataset columns instead of returning unfiltered chart data.


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 merges valid extra_form_data via
merge_extra_form_data_filters_into_query / build_query_context_from_form_data.
However, datasource query construction reports filters naming unknown columns in
rejected_filter_columns, and the MCP tool previously ignored that signal and
returned the unfiltered result as a success. This PR intersects rejected columns
with the filters supplied by the current request and returns a ValidationError
naming them. It supports both filters and adhoc_filters, in saved-chart and
form-data fallback paths, without failing on unrelated stale saved filters.

This PR also adds extra_form_data 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. The shared helper update
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 valid filters, adhoc_filters, and TEMPORAL_RANGE overrides, plus the
    customer-reported unknown-column adhoc_filters case end-to-end through the MCP
    tool, asserting a named ValidationError instead of unfiltered chart data.
  • CI Python unit suite is running against the rebased branch; the prior failure was fixed by providing form_data on the query-context test double.
  • pre-commit run --files <all PR-changed files> — clean locally and in CI.

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

@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 e1995f7
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a8dd214a367c40008e3e126
😎 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 thread tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py Outdated
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

@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 76.92308% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.96%. Comparing base (3585e82) to head (df5d250).
⚠️ Report is 8 commits behind head on master.

Files with missing lines Patch % Lines
superset/mcp_service/chart/tool/get_chart_sql.py 76.47% 7 Missing and 1 partial ⚠️
superset/mcp_service/chart/tool/get_chart_data.py 73.07% 4 Missing and 3 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #43478      +/-   ##
==========================================
+ Coverage   78.93%   78.96%   +0.03%     
==========================================
  Files        2877     2877              
  Lines      165236   165324      +88     
  Branches    38184    38194      +10     
==========================================
+ Hits       130424   130548     +124     
+ Misses      32350    32295      -55     
- Partials     2462     2481      +19     
Flag Coverage Δ
hive 38.00% <9.23%> (-0.02%) ⬇️
mysql 57.73% <9.23%> (-0.02%) ⬇️
postgres 57.77% <9.23%> (-0.03%) ⬇️
presto 39.92% <9.23%> (-0.02%) ⬇️
python 83.63% <76.92%> (+0.06%) ⬆️
sqlite 57.46% <9.23%> (-0.02%) ⬇️
unit 73.71% <76.92%> (+0.06%) ⬆️

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

@aminghadersohi aminghadersohi changed the title fix(mcp): apply extra_form_data filters when rendering chart SQL fix(mcp): honor and validate chart filters Aug 25, 2026
aminghadersohi and others added 10 commits August 25, 2026 17:33
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).
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
aminghadersohi force-pushed the aminghadersohi/fix-get-chart-sql-extra-form-data branch from 503bd06 to e1995f7 Compare August 25, 2026 17:34
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

CI/review sweep complete:

  • Replied directly to both CodeAnt review threads and resolved them. The malformed-filter assertion and stale saved-context fallback are covered by the latest branch.
  • The earlier Bito invalid-filter coverage suggestion is covered by test_malformed_extra_form_data_filter_returns_clean_error; the customer-reported get_chart_data unknown-column case is covered end-to-end by test_unknown_adhoc_filter_column_returns_validation_error.
  • Pulled the failed unit-test logs rather than retriggering. The sole root failure was the test double missing query_context.form_data; fixed by making the mocked loaded query context match the production interface.
  • Rebased onto current origin/master and ran pre-commit across every file changed by the PR successfully.
  • The prior Codecov patch check was green; Netlify comments are deployment status notifications and require no code change.

Latest verified PR head: e1995f71058bb33d4d34b1c5801bfec63a2df94b.

@bito-code-review

bito-code-review Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Code Review Agent Run #463d11

Actionable Suggestions - 0
Review Details
  • Files reviewed - 2 · Commit Range: dfedf65..e1995f7
    • superset/mcp_service/chart/tool/get_chart_data.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.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

The unit-test job failed because the loaded query context test double did
not match the QueryContext surface set_query_context_form_data consumes,
so every saved-context case raised AttributeError instead of exercising
the tool. Make the double serialize like a real QueryObject.

Fixing that surfaced a real defect: ChartDataDatasourceSchema only
requires "id", so a saved query_context that omits "type" loads fine but
then raised an unhandled KeyError out of _sql_from_saved_query_context.
Fall back to the chart's own datasource instead.
@bito-code-review

bito-code-review Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Code Review Agent Run #bc790b

Actionable Suggestions - 0
Review Details
  • Files reviewed - 3 · Commit Range: e1995f7..df5d250
    • superset/mcp_service/chart/tool/get_chart_sql.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

@rusackas
rusackas merged commit 1fd763b into apache:master Aug 26, 2026
77 of 79 checks passed
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.

3 participants