From 3b354e4ab838066a28810ad6cc67c10fd069912b Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Sat, 28 Nov 2026 09:25:48 +0000 Subject: [PATCH] fix(chart-data): don't re-run CSV export query a second time for streaming 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 --- superset/charts/data/api.py | 89 +++++++------------ .../unit_tests/charts/test_chart_data_api.py | 69 +++++++++++--- 2 files changed, 92 insertions(+), 66 deletions(-) diff --git a/superset/charts/data/api.py b/superset/charts/data/api.py index f01df5921f3a..54288fdacb0a 100644 --- a/superset/charts/data/api.py +++ b/superset/charts/data/api.py @@ -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_ @@ -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 @@ -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 def _create_streaming_csv_response( self, diff --git a/tests/unit_tests/charts/test_chart_data_api.py b/tests/unit_tests/charts/test_chart_data_api.py index aae507f389a6..653e0acb64ac 100644 --- a/tests/unit_tests/charts/test_chart_data_api.py +++ b/tests/unit_tests/charts/test_chart_data_api.py @@ -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"] @@ -1554,6 +1556,7 @@ 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() @@ -1561,6 +1564,7 @@ def _csv_export_command( 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 @@ -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", [