Skip to content

fix(mcp): return structured ChartError on SQLAlchemyError in get_chart_sql - #44351

Merged
eschutho merged 8 commits into
masterfrom
fix-mcp-get-chart-sql-detached-instance
Nov 22, 2026
Merged

eschutho merged 8 commits into
masterfrom
fix-mcp-get-chart-sql-detached-instance

Conversation

@eschutho

@eschutho eschutho commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

Problem: get_chart_sql can raise DetachedInstanceError (a SQLAlchemyError) when the chart instance's attributes are lazily reloaded after the session has been torn down. On master nothing catches it, so it propagates to the MCP client as a raw ToolError.

Fix: Add an except SQLAlchemyError handler to the outer get_chart_sql() try/except, mirroring get_chart_preview.py. It logs the full exception server-side (ctx.error + logger.exception) and returns a structured ChartError(error_type="DatabaseError") to the client containing only the exception class name, so no SQL statements or bound parameters are exposed.

This does not prevent the underlying detach; it makes the failure a structured, non-leaking error instead of an unhandled exception.

Decisions made that were not in the instructions

None.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A — backend-only change, no UI changes.

TESTING INSTRUCTIONS

pytest tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py::TestDetachedInstanceError -v

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration
  • Introduces new feature or API
  • Removes existing feature or API

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #cc96a5

Actionable Suggestions - 0
Review Details
  • Files reviewed - 2 · Commit Range: 252c780..252c780
    • 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 [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@codecov

codecov Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 84.45%. Comparing base (209ae7d) to head (e5c09fe).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #44351      +/-   ##
==========================================
- Coverage   85.74%   84.45%   -1.29%     
==========================================
  Files        3113     3067      -46     
  Lines      215653   210222    -5431     
  Branches    51096    48581    -2515     
==========================================
- Hits       184905   177550    -7355     
- Misses      27333    29257    +1924     
  Partials     3415     3415              
Flag Coverage Δ
hive 33.95% <20.00%> (-0.01%) ⬇️
mysql 51.60% <20.00%> (-0.01%) ⬇️
postgres 51.63% <20.00%> (-0.01%) ⬇️
presto 35.62% <20.00%> (-0.01%) ⬇️
python 88.36% <100.00%> (+<0.01%) ⬆️
sqlite 51.30% <20.00%> (-0.01%) ⬇️
unit 83.73% <100.00%> (+<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.

@eschutho
eschutho force-pushed the fix-mcp-get-chart-sql-detached-instance branch from 252c780 to 995c43b Compare September 18, 2026 22:08

@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 #903f7c

Actionable Suggestions - 2
  • superset/mcp_service/chart/tool/get_chart_sql.py - 2
Additional Suggestions - 1
  • tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py - 1
    • Fixture missing return annotation · Line 1212-1212
      BITO.md rule 11810 requires explicit return type annotations on all fixture definitions. The new `mock_db_refresh` fixture (like its sibling `mock_auth`) omits one; a yield-style fixture should be annotated `-> Iterator[None]` with `Iterator` imported from `typing`. A grep shows only 1 of this file's 3 fixtures is annotated, so adding the annotation keeps the new code aligned with the repo typing standard.
Review Details
  • Files reviewed - 2 · Commit Range: 63a28b3..995c43b
    • 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 [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

"identifier=%s, error_type=%s, error=%s"
% (request.identifier, type(e).__name__, str(e))
)
logger.exception("SQLAlchemy error in get_chart_sql: %s", e)

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.

CWE-209: DB Error Detail Leakage

The new handler returns raw SQLAlchemy exception text to the MCP client via ChartError.error; driver messages can embed SQL fragments, constraint/table names, or host details. The ctx.error log already captures full detail server-side. Return a generic message (keep type(e).__name__) and reserve {e} for logs. Note error_type="DatabaseError" is not used elsewhere in chart/tool/ (DataError is). (CWE-209)

Code Review Run #903f7c


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

  • Yes, avoid them

# a later lazy reload (e.g. chart.params in _resolve_effective_form_data,
# chart.query_context in _sql_from_saved_query_context) would then raise
# DetachedInstanceError. See get_chart_preview.py for the same pattern.
db.session.refresh(chart)

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.

Unguarded session refresh

db.session.refresh(chart) is unguarded, but sibling tools guard this exact call: generate_chart.py wraps refresh in try/except SQLAlchemyError and continues, and get_chart_preview.py does the same. A transient metadata-DB failure here now fails the whole request via the new SQLAlchemyError handler for what is a defensive freshness reload. Guard it and continue with a warning, matching the established pattern.

Code Review Run #903f7c


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

  • Yes, avoid them

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

Both production edits are pinned (removing each reds exactly the new tests; no-op control stays green), and the 6 red CI tests are inherited from merge-base 2e1cf8a, fixed on master by 43fee87. Two questions inline.

@eschutho
eschutho force-pushed the fix-mcp-get-chart-sql-detached-instance branch from 995c43b to e7cf387 Compare September 29, 2026 22:03
Comment on lines +465 to +468
return ChartError(
error=f"Chart SQL retrieval failed due to a database session error: {e}",
error_type="DatabaseError",
)

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: Returning str(e) exposes SQLAlchemy details to MCP callers, including possible table names, SQL fragments, constraint names, and connection information.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Security

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

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

**Path:** superset/mcp_service/chart/tool/get_chart_sql.py
**Line:** 465:468
**Comment:**
	*Security: Returning `str(e)` exposes SQLAlchemy details to MCP callers, including possible table names, SQL fragments, constraint names, and connection information.

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
👍 | 👎

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.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of e5c09fe.

The shown handler no longer returns str(e); if resolving a LazyString fails, it returns a generic malformed-result message instead.

If that's not right, unresolve this thread and CodeAnt will leave it open.

@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 #d8518b

Actionable Suggestions - 1
  • tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py - 1
Review Details
  • Files reviewed - 2 · Commit Range: e7cf387..15e673e
    • 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 [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

yield mock_get_user

@pytest.fixture(autouse=True)
def mock_db_refresh(self):

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.

Fixture missing return type

The new mock_db_refresh fixture lacks a return type annotation, which the repo's typing convention mandates for all fixtures, including their return types (BITO.md rules 11810/12490). Annotate it -> Iterator[None] (yield-based fixture) plus the Iterator import. Sibling mock_auth has the same gap but is unchanged code here.

Code Review Run #d8518b


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

  • Yes, avoid them

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Oct 9, 2026
@netlify

netlify Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

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

eschutho and others added 3 commits October 16, 2026 04:57
…078)

Add db.session.refresh(chart) immediately after _find_chart_by_identifier()
returns in _handle_chart_sql_request, mirroring the identical fix already
present in get_chart_preview.py, generate_chart.py, and the dashboard tools.

Without the refresh, the chart ORM instance's attributes expire after the
event_logger.log_context commit (DBEventLogger.log calls session.commit with
expire_on_commit=True). The subsequent await ctx.info/warning calls are real
event-loop yield points, after which accessing chart.params in
_resolve_effective_form_data or chart.query_context in
_sql_from_saved_query_context triggers a lazy reload on a detached session,
raising DetachedInstanceError.

As defense-in-depth, also add an except SQLAlchemyError handler to the outer
get_chart_sql() try/except, so any residual session-related errors return a
structured ChartError instead of propagating as unhandled exceptions.

Fixes SUPERSET-PYTHON-1739

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@eschutho
eschutho force-pushed the fix-mcp-get-chart-sql-detached-instance branch from 8aa1e71 to 7705228 Compare October 16, 2026 04:59
@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟢  Low Risk

  • The PR appears safe to merge; the database error response exposes only the exception type, not sensitive SQLAlchemy details.

Assessed commit: e5c09fe29c8e

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Oct 16, 2026
…rror handler

chart.datasource_type is read right after lookup and already triggers
SQLAlchemy's load of all expired column attributes, so the explicit
refresh added no extra loading. Tests now exercise the SQLAlchemyError
handler via validate_chart_dataset.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@pull-request-size pull-request-size Bot added size/M and removed size/L labels Oct 22, 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.

Please drop the private Shortcut and Sentry links from this public description.

The title and description still describe the eager db.session.refresh() fix that 1daf090 removed; the diff now only maps SQLAlchemyError to a ChartError, so DetachedInstanceError is reported, not avoided.

@eschutho eschutho changed the title fix(mcp): eagerly refresh chart after lookup in get_chart_sql to avoid DetachedInstanceError fix(mcp): return structured ChartError on SQLAlchemyError in get_chart_sql Oct 23, 2026
@eschutho
eschutho merged commit 79870cc into master Nov 22, 2026
78 checks passed
@eschutho
eschutho deleted the fix-mcp-get-chart-sql-detached-instance branch November 22, 2026 23:01
jprinet added a commit to jprinet/superset that referenced this pull request Nov 23, 2026
* origin/master: (393 commits)
  fix(a11y): name the semantic view description input (apache#46458)
  docs(semantic): explain datasource list modification eligibility (apache#46462)
  docs(semantic-layer): document NULL-preserving exclusion filters (apache#46447)
  fix(uploads): skip folder and system entries in columnar ZIP uploads (apache#45617)
  fix(i18n-es): promote 47 of the zero-context backfill entries (apache#45847)
  fix(mcp): return structured ChartError on SQLAlchemyError in get_chart_sql (apache#44351)
  fix(datasets): follow semantic view modification permissions (apache#46448)
  fix(docker): account for container memory limits in frontend-mem-nag.sh (apache#46373)
  fix(reports): carry the report's native filters in the email and Slack link (apache#46062)
  fix(explore): apply the dataset timezone to grained temporal filter values (apache#46175)
  fix(i18n): enforce the do-not-translate registry across the catalogs (apache#45974)
  chore(logging): log unparseable virtual dataset SQL at debug in the RLS lookup (apache#46139)
  fix(i18n): split parameter-suggestion plural into two messages (apache#46049)
  test(partition-mapping): cover Hive/Impala mirrored SQL, cache outage and migration (apache#46319)
  perf(dashboard): look up the dashboard once per filter_state read (apache#46314)
  fix(i18n): load the dayjs locale for every language with a catalog (apache#45982)
  test(semantic-layer): make date export parametrization deterministic (apache#46449)
  fix(oauth2): idempotent OAuth2 completion and resilient listener (apache#40292)
  fix(explore): prevent full table scan when SQL expression is used as x-axis (apache#41339)
  feat(mcp): radar chart type plugin (apache#43571)
  ...

# Conflicts:
#	.github/workflows/docker.yml
#	.github/workflows/superset-frontend.yml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants