Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 34 additions & 55 deletions superset/charts/data/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,18 +632,20 @@ def _send_chart_response( # noqa: C901
# and the factory-resolved slice covers the rest.
slice_ = slice_ or materialized_result["query_context"].slice_

# Check if we should use streaming for large datasets
if is_csv_format and self._should_use_streaming(
materialized_result,
form_data,
):
return self._create_streaming_csv_response(
materialized_result,
form_data,
filename=filename,
expected_rows=expected_rows,
slice_=slice_,
)
# Streaming for large datasets is decided *before* the regular
# query execution above, in ``_should_stream_before_execution``
# (see its caller in ``_get_data_response``). By this point
# ``command.execute()`` has already run the query and fetched
# every row into ``materialized_result``, so there is no longer
# any memory/latency benefit to re-running the same SQL through
# ``StreamingCSVExportCommand`` -- doing so only pays for a
# second round trip and, on warehouses such as Redshift that
# restrict a connection to a single open (named) cursor, risks
# a `psycopg2.errors.InvalidCursorState: opening multiple
# cursors from within the same client connection is not
# allowed` if the two queries' cursors ever overlap. Fall
# through to the regular (already-fetched) CSV response below
# instead of re-executing.

export_filename = filename or self._get_default_export_filename(
form_data, slice_
Expand Down Expand Up @@ -976,6 +978,19 @@ def _should_stream_before_execution(
tables need the regular execution path. Multi-query contexts also stay
on the regular path: the streaming command exports a single query,
while the regular path bundles every query into a zip.
A configured ``row_limit`` is also checked, so clients that don't send
``expected_rows`` (e.g. calling this API directly) still stream once the
requested row count is large enough. This decision must be made before
``command.execute()`` runs the query: by the time a row count can be
read back from an executed result, the whole result set is already
fetched into memory, so re-running the same SQL through
``StreamingCSVExportCommand`` afterwards would only add a redundant
second query -- and, on warehouses that restrict a connection to a
single open cursor (e.g. Redshift), risks
``psycopg2.errors.InvalidCursorState: opening multiple cursors from
within the same client connection is not allowed`` if the two
queries' cursors ever overlap.
"""
if len(query_context.queries) != 1:
return False
Expand All @@ -984,49 +999,13 @@ def _should_stream_before_execution(
if query_context.result_type != ChartDataResultType.FULL:
return False
threshold = app.config.get("CSV_STREAMING_ROW_THRESHOLD", 100000)
return (expected_rows is not None and expected_rows >= threshold) or (
tree_export_uses_streaming(query_context.form_data)
)

def _should_use_streaming(
self, result: dict[Any, Any], form_data: dict[str, Any] | None = None
) -> bool:
"""Determine if streaming should be used based on actual row count threshold."""
query_context = result["query_context"]
result_format = query_context.result_format

# Only support CSV streaming currently
if result_format.lower() != "csv":
return False

# Get streaming threshold from config
threshold = app.config.get("CSV_STREAMING_ROW_THRESHOLD", 100000)

# Extract actual row count (same logic as frontend)
actual_row_count: int | None = None
viz_type = form_data.get("viz_type") if form_data else None

# For table viz, try to get actual row count from query results
if viz_type == "table" and result.get("queries"):
# Check if we have rowcount in the second query result (like frontend does)
queries = result.get("queries", [])
if len(queries) > 1 and queries[1].get("data"):
data = queries[1]["data"]
if isinstance(data, list) and len(data) > 0:
rowcount = data[0].get("rowcount")
actual_row_count = int(rowcount) if rowcount else None

# Fallback to row_limit if actual count not available
if actual_row_count is None:
if form_data and "row_limit" in form_data:
row_limit = form_data.get("row_limit", 0)
actual_row_count = int(row_limit) if row_limit else 0
elif query_context.form_data and "row_limit" in query_context.form_data:
row_limit = query_context.form_data.get("row_limit", 0)
actual_row_count = int(row_limit) if row_limit else 0

# Use streaming if row count meets or exceeds threshold
return actual_row_count is not None and actual_row_count >= threshold
if expected_rows is not None and expected_rows >= threshold:
return True
if tree_export_uses_streaming(query_context.form_data):
return True
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
Comment on lines +1006 to +1008

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


def _create_streaming_csv_response(
self,
Expand Down
69 changes: 58 additions & 11 deletions tests/unit_tests/charts/test_chart_data_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1448,28 +1448,30 @@ def test_streaming_csv_response_uses_chart_name(app: SupersetApp) -> None:
The generated streaming CSV filename (used when the client didn't
supply one) must include the chart's name, matching the non-streaming
path.

This exercises ``_create_streaming_csv_response`` directly, the way
``_get_data_response``/``_should_stream_before_execution`` call it
*before* the regular query execution -- never through
``_send_chart_response`` after a result is already materialized. Doing
the latter would re-run the chart's SQL a second time purely to stream
data already sitting in memory, which is exactly the redundant query
that let `Error in streaming CSV generator: ... InvalidCursorState`
reach Redshift connections restricted to a single open cursor.
"""
query_context = MagicMock()
query_context.result_type = ChartDataResultType.FULL
query_context.result_format = ChartDataResultFormat.CSV
query_context.slice_ = MagicMock(slice_name="Quarterly Revenue")

result = {
"query_context": query_context,
"queries": [{"data": "col_a,col_b\n1,2\n"}],
}

api = ChartDataRestApi()
with (
app.test_request_context("/api/v1/chart/data"),
patch("superset.charts.data.api.security_manager") as mock_security_manager,
patch("superset.charts.data.api.is_feature_enabled", return_value=False),
patch.object(ChartDataRestApi, "_should_use_streaming", return_value=True),
patch("superset.charts.data.api.StreamingCSVExportCommand"),
):
mock_security_manager.can_access.return_value = True
response = api._send_chart_response(
result, form_data={"viz_type": "table", "row_limit": 10}
response = api._create_streaming_csv_response(
{"query_context": query_context},
form_data={"viz_type": "table", "row_limit": 10},
slice_=query_context.slice_,
)

assert "Quarterly_Revenue" in response.headers["Content-Disposition"]
Expand Down Expand Up @@ -1554,13 +1556,15 @@ def _csv_export_command(
result_format: ChartDataResultFormat = ChartDataResultFormat.CSV,
result_type: ChartDataResultType = ChartDataResultType.FULL,
num_queries: int = 1,
form_data: dict[str, Any] | None = None,
) -> MagicMock:
"""Build a chart-data command mock whose query context looks like an export."""
command = MagicMock()
command.query_context.result_format = result_format
command.query_context.result_type = result_type
command.query_context.slice_ = None
command.query_context.queries = [MagicMock() for _ in range(num_queries)]
command.query_context.form_data = form_data or {}
return command


Expand Down Expand Up @@ -1606,6 +1610,49 @@ def test_get_data_response_streams_large_csv_without_executing(
)


def test_get_data_response_streams_large_row_limit_without_executing(
app: SupersetApp,
) -> None:
"""
A large ``row_limit`` must also decide streaming before execution, even
when the client didn't send ``expected_rows`` (e.g. a direct API call).

Before this, that case fell through to the regular path: ``command.execute()``
ran and fully materialized the result, and only afterwards -- now that the
whole result set was already fetched -- did a post-hoc check decide to
stream it, which re-ran the identical SQL a second time through
``StreamingCSVExportCommand``. That redundant second query is what let
``psycopg2.errors.InvalidCursorState: opening multiple cursors from
within the same client connection is not allowed`` reach Redshift
connections, which do not allow a second open cursor before the first is
closed.
"""
command = _csv_export_command(form_data={"row_limit": 380273})
api = ChartDataRestApi()
streamed: MagicMock = MagicMock()

with (
app.test_request_context("/api/v1/chart/data"),
patch.dict(app.config, {"CSV_STREAMING_ROW_THRESHOLD": 100000}),
patch(
"superset.charts.data.api.security_manager", new_callable=MagicMock
) as mock_security_manager,
patch("superset.charts.data.api.is_feature_enabled", return_value=False),
patch.object(
api, "_create_streaming_csv_response", return_value=streamed
) as mock_stream,
):
mock_security_manager.can_access.return_value = True
response = api._get_data_response(
command,
form_data={"viz_type": "table", "row_limit": 380273},
)

assert response is streamed
command.execute.assert_not_called()
mock_stream.assert_called_once()


@pytest.mark.parametrize(
"result_format,result_type,expected_rows",
[
Expand Down
Loading