Skip to content

fix(mcp): snapshot chart fields in get_chart_data before session expiry - #44004

Merged
geido merged 3 commits into
masterfrom
fix/mcp-get-chart-data-detached-instance
Sep 14, 2026
Merged

geido merged 3 commits into
masterfrom
fix/mcp-get-chart-data-detached-instance

Conversation

@geido

@geido geido commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

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 (Instance <Slice at 0x...> is not bound to a Session; attribute refresh operation cannot proceed). The tool's broad except (..., 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_helpers query builders) also read chart attributes long after those commits, so they receive a _ChartFacts NamedTuple rather than the ORM instance. Its field names match the Slice columns, so helpers reading chart.viz_type or getattr(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 sibling get_chart_preview tool. Review showed that does not fix this bug. refresh() runs inside the chart_lookup log context, and exiting that block commits — expiring exactly what refresh() just loaded. Verified directly:

load → … → commit → detach → read chart.id
no refresh (master) DetachedInstanceError
refresh() only DetachedInstanceError
snapshot to locals OK

Chart reads in this function are interleaved with four committing log_context blocks, so no placement of refresh() 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

  • The not-found return moved inside the lookup block so the snapshot can be unconditional. The log context still records the action on that path (a return from a @contextmanager body still runs the exit).
  • The 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 only id, slice_name and viz_type — no relationship access — so handing them _ChartFacts loses nothing.
  • Known remaining exposure, not addressed here: guest_scope.authorize_query(query_context, guest_dashboard_id, chart) still takes the ORM instance, because query_context.slice_ needs the real Slice. The guest path can therefore still read a detached instance. Likewise chart.table.metrics remains reachable only while the related SqlaTable is live — expunging the Slice does 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, csv and excel.

pytest tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py -q
pytest tests/unit_tests/mcp_service/ -q

To confirm the test is not vacuous, restore get_chart_data.py from master and re-run it: all three parametrizations fail with error_type=DetachedInstanceError, reproducing the original failure.

Results on this branch

Run Result
test_get_chart_data.py 112 passed
tests/unit_tests/mcp_service/ 3736 passed, 1 failed
pre-commit run (mypy, ruff, pylint, all hooks) all pass

The single failure is test_mcp_e2e_smoke.py::test_tools_call_health_check_over_real_asgi_transport, which fails identically on unmodified master — pre-existing and unrelated.

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

🤖 Generated with Claude Code

@netlify

netlify Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

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

@codecov

codecov Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.85714% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.10%. Comparing base (08e686b) to head (220201c).
⚠️ Report is 118 commits behind head on master.

Files with missing lines Patch % Lines
superset/mcp_service/chart/tool/get_chart_data.py 82.85% 5 Missing and 1 partial ⚠️
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     
Flag Coverage Δ
hive 37.33% <20.00%> (-0.10%) ⬇️
mysql 56.85% <20.00%> (-0.19%) ⬇️
postgres 56.88% <20.00%> (-0.18%) ⬇️
presto 39.21% <20.00%> (-0.11%) ⬇️
python 84.56% <82.85%> (+0.10%) ⬆️
sqlite 56.58% <20.00%> (-0.18%) ⬇️
unit 75.90% <82.85%> (+0.21%) ⬆️

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.

@geido geido changed the title fix(mcp): refresh chart after lookup in get_chart_data fix(mcp): snapshot chart fields in get_chart_data before session expiry Sep 8, 2026
@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 9, 2026
@geido
geido force-pushed the fix/mcp-get-chart-data-detached-instance branch from c3f16bf to 67e72bf Compare September 9, 2026 14:02
@geido
geido marked this pull request as ready for review September 9, 2026 14:34
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]>
@geido
geido force-pushed the fix/mcp-get-chart-data-detached-instance branch from 9213584 to 47f0e5f Compare September 9, 2026 14:45

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

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.

@bito-code-review

Copy link
Copy Markdown
Contributor

The current implementation addresses the detachment issue by capturing the necessary chart attributes into a _ChartFacts named tuple while the ORM instance is still attached. This ensures that downstream helpers, which run after session commits and await points, operate on stable, detached-safe values rather than the potentially expired ORM instance.

To further harden the guest authorization path, you could consider re-fetching the Slice object within the authorization scope if the initial instance is detected as detached, or explicitly re-attaching it to the current session. Extending the regression test to specifically trigger a detachment scenario—such as by introducing an artificial await point or session commit between the initial lookup and the authorization call—would verify that the guest authorization and tamper guard logic correctly handle the detached state.

superset/mcp_service/chart/tool/get_chart_data.py

class _ChartFacts(NamedTuple):
    """Chart values copied off the Slice while it is still session-attached.
    ..."""
    id: int
    slice_name: str | None
    viz_type: str | None
    datasource_id: Any = None
    datasource_type: str | None = None

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Sep 9, 2026
@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #f6f987

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

Documentation & Help

AI Code Review powered by Bito Logo

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]>
@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #855d83

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

Documentation & Help

AI Code Review powered by Bito Logo

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

The follow-up closes the remaining embedded-guest path: authorization gets a fresh, guest-filtered Slice, and a missing re-fetch fails closed. I reran the focused test file at a07f05c (134 passed). Approving this head.

for q in data.get("queries", [])
],
form_data={},
slice_=None,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +3122 to +3124
assert stored_chart.id == 9
assert stored_chart.query_context is not None
assert stored_chart.params_dict == {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These assert on the SimpleNamespace built above, so they can't fail. stored_chart is attached is the real check.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: patch and Client are already imported at module level (lines 26/29), same at 3038-3040.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@geido
geido merged commit 2eccf3b into master Sep 14, 2026
83 checks passed
@geido
geido deleted the fix/mcp-get-chart-data-detached-instance branch September 14, 2026 16:28
@bito-code-review

Copy link
Copy Markdown
Contributor

Bito Automatic Review Skipped – PR Already Merged

Bito scheduled an automatic review for this pull request, but the review was skipped because this PR was merged before the review could be run.
No action is needed if you didn't intend to review it. To get a review, you can type /review in a comment and save it

@gabotorresruiz gabotorresruiz mentioned this pull request Sep 15, 2026
2 of 9 tasks
villebro pushed a commit that referenced this pull request Sep 16, 2026
…ry (#44004)

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
(cherry picked from commit 2eccf3b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants