Skip to content

fix(chart-data): don't re-run CSV export query a second time for streaming (SUPERSET-PYTHON-1D6E) - #46677

Open
eschutho wants to merge 1 commit into
apache:masterfrom
eschutho:fix-sentry-1D6E-csv-cursor
Open

eschutho wants to merge 1 commit into
apache:masterfrom
eschutho:fix-sentry-1D6E-csv-cursor

Conversation

@eschutho

Copy link
Copy Markdown
Member

Summary

Fixes Sentry issue SUPERSET-PYTHON-1D6E: Error in streaming CSV generator: (psycopg2.errors.InvalidCursorState) opening multiple cursors from within the same client connection is not allowed. (fired once, on /api/v1/chart/1028/data/).

ChartDataRestApi._send_chart_response() had a post-execution streaming check, _should_use_streaming(), that ran only after command.execute() had already run the chart's SQL and fully materialized every row into materialized_result. When that check decided the result was large enough to warrant streaming, it re-executed the identical SQL a second time through StreamingCSVExportCommand, purely to produce a "streamed" response for data that was already sitting fully in memory.

Running the query twice is pointless once the first execution already holds the full result, and on warehouses such as Redshift — which reject a second open named/server-side cursor on a connection before the first is closed — overlapping first/second-query cursors can surface exactly this InvalidCursorState error. (There's already a sibling code path, _should_stream_before_execution, with a comment explicitly warning against this pattern — but it only covered the case where the frontend sends expected_rows; the actual-row-count fallback path still executed first then streamed.)

Fix

  • Extend _should_stream_before_execution (used in _get_data_response, before command.execute() runs) to also honor a large row_limit read directly from form_data/query_context.form_data, covering the case the removed post-execution check existed for — but deciding it before any query runs, so the query is never executed twice.
  • Remove the now-dead _should_use_streaming method and its call site in _send_chart_response. By the time that call site is reached, the result is already fully fetched, so falling through to the regular (already-fetched) CSV response is strictly better than re-querying.

Test plan

  • Added test_get_data_response_streams_large_row_limit_without_executing, asserting a large row_limit streams without ever calling command.execute().
  • Updated test_streaming_csv_response_uses_chart_name to exercise _create_streaming_csv_response directly (the way it is now always invoked — before execution) instead of patching the removed _should_use_streaming.
  • Ran locally: ruff check / ruff format --check (clean) on both touched files, and the full tests/unit_tests/charts/ suite — 912 passed, 2 xfailed.
  • Could not run: mypy (pre-existing, unrelated numpy stub incompatibility in this sandbox, unrelated to this change) or any integration/DB-backed test (no live Redshift/Postgres warehouse available in this environment) — the original bug report is DB-specific (Redshift), so it can't be reproduced deterministically without one.

🤖 Generated with Claude Code

…aming

Sentry SUPERSET-PYTHON-1D6E: "Error in streaming CSV generator:
(psycopg2.errors.InvalidCursorState) opening multiple cursors from
within the same client connection is not allowed."

ChartDataRestApi._send_chart_response() had a post-execution streaming
check (_should_use_streaming) that ran *after* command.execute() had
already fully executed the chart's SQL and materialized every row.
When it decided the result was large enough to stream, it re-executed
the identical SQL again via StreamingCSVExportCommand just to produce
a "streamed" response for data that was already sitting in memory.

Running the same query twice is unnecessary once the first execution
has the full result, and on warehouses such as Redshift -- which
reject opening a second named/server-side cursor before the first is
closed -- the overlapping queries can surface exactly this
InvalidCursorState error.

Fix: decide whether to stream before executing, extending the existing
pre-execution check (_should_stream_before_execution, used when the
frontend sends expected_rows) to also honor a large row_limit directly
from form_data/query_context. This covers the case the removed
post-execution check existed for, without ever running the query
twice. The post-execution _should_use_streaming method and its call
site are removed as dead weight.

Tests: added a unit test asserting a large row_limit streams without
calling command.execute(), and updated the existing streaming-filename
test to exercise _create_streaming_csv_response directly (the way it's
now always invoked -- before execution) instead of patching the
removed _should_use_streaming method.

Locally ran: ruff check/format (clean) and the full
tests/unit_tests/charts/ suite (912 passed, 2 xfailed) against this
checkout's superset-core sources. Could not run mypy (pre-existing,
unrelated numpy stub incompatibility in this sandbox) or any
integration/DB-backed test (no live warehouse available here).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@github-actions github-actions Bot added the api Related to the REST API label Nov 28, 2026
Comment on lines +1006 to +1008
form_data = query_context.form_data or {}
row_limit = form_data.get("row_limit")
return row_limit is not None and int(row_limit) >= threshold

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: When row_limit is set only on queries[0], this check misses it and executes a large CSV query fully in memory instead of streaming.

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes · 🏷️ Performance

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/charts/data/api.py
**Line:** 1006:1008
**Comment:**
	*Performance: When `row_limit` is set only on `queries[0]`, this check misses it and executes a large CSV query fully in memory instead of streaming.

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

@codeant-ai-for-open-source

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟡  Medium Risk

  • The PR needs attention before merging.
  • Streaming selection checks only query_context.form_data.row_limit, so a limit stored on queries[0] can still materialize a large CSV result in memory.

Assessed commit: 3b354e4ab838

@codecov

codecov Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.42%. Comparing base (479e008) to head (3b354e4).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #46677      +/-   ##
==========================================
- Coverage   86.42%   86.42%   -0.01%     
==========================================
  Files        3183     3183              
  Lines      222606   222585      -21     
  Branches    52996    52990       -6     
==========================================
- Hits       192385   192366      -19     
- Misses      26752    26754       +2     
+ Partials     3469     3465       -4     
Flag Coverage Δ
hive 33.64% <0.00%> (+<0.01%) ⬆️
mysql 51.83% <100.00%> (+<0.01%) ⬆️
postgres 51.85% <100.00%> (+<0.01%) ⬆️
presto 35.33% <0.00%> (+<0.01%) ⬆️
python 88.81% <100.00%> (+<0.01%) ⬆️
sqlite 51.55% <100.00%> (+<0.01%) ⬆️
unit 84.37% <71.42%> (+<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.

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

Nice

@tarunchaudharydev

Copy link
Copy Markdown
Contributor

I would like to work on this issue.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Related to the REST API size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants