Repository navigation
fix(mcp): return structured ChartError on SQLAlchemyError in get_chart_sql - #44351
Conversation
Code Review Agent Run #cc96a5Actionable 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 |
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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:
|
252c780 to
995c43b
Compare
There was a problem hiding this comment.
Code Review Agent Run #903f7c
Actionable Suggestions - 2
-
superset/mcp_service/chart/tool/get_chart_sql.py - 2
- CWE-209: DB Error Detail Leakage · Line 464-464
- Unguarded session refresh · Line 531-531
Additional Suggestions - 1
-
tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py - 1
-
Fixture missing return annotation · Line 1212-1212BITO.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
| "identifier=%s, error_type=%s, error=%s" | ||
| % (request.identifier, type(e).__name__, str(e)) | ||
| ) | ||
| logger.exception("SQLAlchemy error in get_chart_sql: %s", e) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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
995c43b to
e7cf387
Compare
| return ChartError( | ||
| error=f"Chart SQL retrieval failed due to a database session error: {e}", | ||
| error_type="DatabaseError", | ||
| ) |
There was a problem hiding this comment.
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
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 fixThere was a problem hiding this comment.
✅ 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.
There was a problem hiding this comment.
Code Review Agent Run #d8518b
Actionable Suggestions - 1
-
tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py - 1
- Fixture missing return type · Line 1212-1212
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
| yield mock_get_user | ||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def mock_db_refresh(self): |
There was a problem hiding this comment.
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
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
…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]>
…ients Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
8aa1e71 to
7705228
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
aminghadersohi
left a comment
There was a problem hiding this comment.
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.
…ceError test Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
* 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
SUMMARY
Problem:
get_chart_sqlcan raiseDetachedInstanceError(aSQLAlchemyError) when the chart instance's attributes are lazily reloaded after the session has been torn down. Onmasternothing catches it, so it propagates to the MCP client as a rawToolError.Fix: Add an
except SQLAlchemyErrorhandler to the outerget_chart_sql()try/except, mirroringget_chart_preview.py. It logs the full exception server-side (ctx.error+logger.exception) and returns a structuredChartError(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
ADDITIONAL INFORMATION