Repository navigation
fix(mcp): snapshot chart fields in get_chart_data before session expiry - #44004
Conversation
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #44004 +/- ##
==========================================
+ Coverage 80.03% 80.10% +0.06%
==========================================
Files 2920 2921 +1
Lines 171598 172249 +651
Branches 39776 39901 +125
==========================================
+ Hits 137332 137973 +641
+ Misses 31684 31678 -6
- Partials 2582 2598 +16
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:
|
c3f16bf to
67e72bf
Compare
get_chart_data reads the chart Slice throughout a long async function. Exiting an event_logger.log_context() commits the session (DBEventLogger.log -> db.session.commit), and with the default expire_on_commit=True that commit expires every loaded attribute. If the instance is also detached before the next read, that read raises DetachedInstanceError, which the broad SQLAlchemyError handler turns into a confusing internal-session error instead of chart data. Copy the values the function needs into plain locals immediately after the lookup, while the instance is still attached. Locals are immune to both expiry and detachment. Chart reads here are interleaved with four committing log_context blocks, so keeping the ORM object alive across them is not workable; db.session.refresh() in particular does not help, because the next commit expires exactly what it just loaded. The export helpers and the two chart_helpers query builders also read chart attributes long after those commits, so they are handed a _ChartFacts NamedTuple instead of the ORM instance. Its field names match the Slice columns, so helpers reading chart.viz_type or getattr(chart, "datasource_id", None) behave identically. Audited: those consumers touch only id, slice_name, viz_type, datasource_id and datasource_type. guest_scope still receives the real Slice, since query_context.slice_ needs the mapped object. The subqueryload(Slice.table).subqueryload(SqlaTable.metrics) eager-load from 39483 is untouched. The not-found return moves inside the lookup block so the snapshot can be unconditional; the log context still records the action on that path. Regression test drives the tool end to end with a chart that detaches at the end of the lookup block, for json, csv and excel. It fails against master's get_chart_data on all three and passes here. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
9213584 to
47f0e5f
Compare
EnxDev
left a comment
There was a problem hiding this comment.
Thanks for tightening the ORM lifetime here—the scalar snapshot keeps the normal JSON/CSV/Excel paths from reaching back into an expired Slice. I found one supported path that still carries the original ORM object past the lookup commit, so I think this needs one more pass before merge; I left the details and a regression-test shape inline. Separately, the pre-commit job is red only because ruff-format rewrites the new test file.
|
The current implementation addresses the detachment issue by capturing the necessary chart attributes into a To further harden the guest authorization path, you could consider re-fetching the superset/mcp_service/chart/tool/get_chart_data.py |
Code Review Agent Run #f6f987Actionable 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 |
The scalar snapshot keeps the ordinary paths off the expired Slice, but the embedded-guest path still handed the looked-up instance to guest_scope.authorize_query, which pins it as query_context.slice_. security_manager.query_context_modified then reads id, query_context and params_dict off that instance during the tamper check. The lookup's log context has committed by then, so on a detached Slice the guest request ended as InternalError. Re-fetch through the DAO instead, so the guard reads a live instance and the guest's ChartFilter still applies. Snapshotted values cannot stand in here: the guard compares the guest payload against the stored chart, so it has to read the stored chart itself. A re-fetch that comes back empty fails closed with NotFound. With this the ORM instance no longer escapes the lookup block at all. Adds a guest regression test that runs the real authorize_query after the chart detaches and asserts the pinned chart is the re-fetched one and that all three attributes the guard reads are readable. It fails without the re-fetch with the reported "not bound to a Session ... (attribute: id)". Also adds the blank line ruff-format wanted between the merged-in xlsxwriter test and the detach fixture. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Code Review Agent Run #855d83Actionable 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 |
| for q in data.get("queries", []) | ||
| ], | ||
| form_data={}, | ||
| slice_=None, |
There was a problem hiding this comment.
With slice_=None hard-coded and ChartDataCommand patched out, this never covers the common case where the factory already pinned slice_ from form_data.slice_id, and never runs query_context_modified itself. Worth a variant for that?
There was a problem hiding this comment.
Added in 220201c — test_guest_authorization_with_slice_already_pinned_by_the_factory.
Traced it: QueryContextFactory.create() pins slice_ from form_data.slice_id (query_context_factory.py:69-70), and ChartDataQueryContextSchema.load() goes through that factory via make_query_context, so a saved chart normally arrives with slice_ set and authorize_query's assignment is skipped (guest_scope.py:61). The new variant covers that branch: it asserts the pre-pinned slice_ is left alone, while the re-fetched chart is still what pins form_data["slice_id"] — which is the read that raises on a detached instance, so the re-fetch matters on this path too. Both guest tests now fail without it.
It also calls the real query_context_modified instead of patching it out. I assert it returns a bool rather than a specific verdict — the point is that reaching into id / query_context / params_dict doesn't raise, and the True/False outcome depends on payload-comparison details that would make the test brittle without testing anything this PR changes.
| assert stored_chart.id == 9 | ||
| assert stored_chart.query_context is not None | ||
| assert stored_chart.params_dict == {} |
There was a problem hiding this comment.
These assert on the SimpleNamespace built above, so they can't fail. stored_chart is attached is the real check.
There was a problem hiding this comment.
Correct — those three read values straight off the SimpleNamespace the test had just constructed, so they could never fail. Removed. stored_chart is attached plus the form_data["slice_id"] wiring are the assertions that can actually break, and the new variant exercises the guard for real.
| an internal-session error instead of chart data. The chart is detached at | ||
| the end of the lookup block, right after its last legitimate ORM use. | ||
| """ | ||
| from unittest.mock import patch |
There was a problem hiding this comment.
nit: patch and Client are already imported at module level (lines 26/29), same at 3038-3040.
There was a problem hiding this comment.
Removed both shadowing import blocks.
…ests Addresses review feedback on the guest coverage. The existing test hard-coded slice_=None, which only exercises the branch where authorize_query assigns it. QueryContextFactory.create() pins slice_ from form_data.slice_id, and ChartDataQueryContextSchema.load() goes through that factory, so a saved chart normally reaches authorize_query with slice_ already set and the assignment is skipped. Adds a variant for that path, asserting an already-pinned slice_ is left alone while the re-fetched chart is still what pins form_data slice_id -- the read that raises when the chart is detached. Both guest tests now fail without the re-fetch. The variant also calls the real security_manager.query_context_modified rather than patching it out, since the point is that the guard can reach into id, query_context and params_dict without raising. It is asserted to return a bool, not a specific verdict: the verdict depends on payload comparison details that are not what these tests are about. Drops three assertions that read values straight off the SimpleNamespace the test had just built, so they could not fail. The identity check on the pinned chart is the real assertion, plus the slice_id wiring. Also drops local patch/Client imports that shadow the module-level ones. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Bito Automatic Review Skipped – PR Already Merged |
…ry (#44004) Co-authored-by: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit 2eccf3b)
SUMMARY
get_chart_datareads the chartSlicethroughout a long async function. Exiting anevent_logger.log_context(...)commits the session (DBEventLogger.log()→db.session.commit()), and with the defaultexpire_on_commit=Truethat commit expires every loaded attribute. If the instance is also detached before the next read, that read raisesDetachedInstanceError(Instance <Slice at 0x...> is not bound to a Session; attribute refresh operation cannot proceed). The tool's broadexcept (..., SQLAlchemyError, ...)handler swallows it and returns a confusing internal-session error instead of chart data.The fix is to stop reading the ORM object after the lookup. The values the function needs are copied into plain locals immediately after the chart is loaded, while the instance is guaranteed attached. Locals are immune to both expiry and detachment.
Downstream consumers (the CSV/Excel export helpers, and the two
chart_helpersquery builders) also read chart attributes long after those commits, so they receive a_ChartFactsNamedTuple rather than the ORM instance. Its field names match the Slice columns, so helpers readingchart.viz_typeorgetattr(chart, "datasource_id", None)behave identically.Note on the first commit in this PR. It applied
db.session.refresh(chart), mirroring the fix in the siblingget_chart_previewtool. Review showed that does not fix this bug.refresh()runs inside thechart_lookuplog context, and exiting that block commits — expiring exactly whatrefresh()just loaded. Verified directly:chart.idDetachedInstanceErrorrefresh()onlyDetachedInstanceErrorChart reads in this function are interleaved with four committing
log_contextblocks, so no placement ofrefresh()survives to the later reads.refresh()was dropped entirely in a follow-up commit: with the fields snapshotted it bought nothing, and it re-runs the eager-load chain, doubling the lookup from 3 queries to 6 on a path that runs on every call.Other notes
returnfrom a@contextmanagerbody still runs the exit).subqueryload(Slice.table).subqueryload(SqlaTable.metrics)eager-load from fix(mcp): eager-load dataset.metrics to prevent Excel export DetachedInstanceError #39483 is untouched, so dataset.metrics preloading still applies. The CSV/Excel helpers were audited and read onlyid,slice_nameandviz_type— no relationship access — so handing them_ChartFactsloses nothing.guest_scope.authorize_query(query_context, guest_dashboard_id, chart)still takes the ORM instance, becausequery_context.slice_needs the realSlice. The guest path can therefore still read a detached instance. Likewisechart.table.metricsremains reachable only while the relatedSqlaTableis live — expunging theSlicedoes not protect it, since that is a separate instance. Both are separate changes.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Not applicable — no UI change.
TESTING INSTRUCTIONS
The regression test drives the tool end to end with a chart that detaches at the end of the lookup block — right after its last legitimate ORM use — and asserts real chart data comes back, for
json,csvandexcel.To confirm the test is not vacuous, restore
get_chart_data.pyfrommasterand re-run it: all three parametrizations fail witherror_type=DetachedInstanceError, reproducing the original failure.Results on this branch
test_get_chart_data.pytests/unit_tests/mcp_service/pre-commit run(mypy, ruff, pylint, all hooks)The single failure is
test_mcp_e2e_smoke.py::test_tools_call_health_check_over_real_asgi_transport, which fails identically on unmodifiedmaster— pre-existing and unrelated.ADDITIONAL INFORMATION
🤖 Generated with Claude Code