sadpandajoe commented on code in PR #45348:
URL: https://github.com/apache/superset/pull/45348#discussion_r4291147651
##########
superset/sql/execution/executor.py:
##########
@@ -404,6 +410,129 @@ def execute_sql_with_cursor(
return results
+def _decode_async_results_payload(blob: bytes) -> dict[str, Any]:
+ """
+ Decode a results backend blob written by the async SQL execution task.
+
+ The task stores a zlib-compressed payload serialized either as MessagePack
+ or as UTF-8 JSON, depending on ``RESULTS_BACKEND_USE_MSGPACK``. The format
+ is detected from the payload itself (a JSON object starts with ``{``, which
+ is never the first byte of a MessagePack map), so results stay readable if
+ the setting differs between the writing worker and the reading process.
+
+ :param blob: Compressed payload read from the results backend
+ :returns: The deserialized payload
+ """
+ decompressed = cast(bytes, utils.zlib_decompress(blob, decode=False))
+ if decompressed.lstrip()[:1] == b"{":
+ return json.loads(decompressed)
+ return msgpack.loads(decompressed, raw=False)
+
+
+def _decode_async_statement_data(stmt_data: dict[str, Any]) -> pd.DataFrame |
None:
+ """
+ Convert one stored statement's data into a DataFrame.
+
+ SELECT results are Arrow IPC bytes (MessagePack) or Base64 strings (JSON).
+ Older JSON payloads contain records; DML statements store ``None``. A
+ SELECT returning no rows yields an empty DataFrame that keeps its columns,
+ matching the synchronous execution path.
+
+ :param stmt_data: Statement entry from the stored payload
+ :returns: DataFrame of the statement rows, or ``None`` for DML
+ """
+ data = stmt_data.get("data")
+ if data is None:
+ return None
+
+ if isinstance(data, str):
+ data = base64.b64decode(data)
+ if isinstance(data, (bytes, bytearray, memoryview)):
+ from superset.result_set import SupersetResultSet
+
+ table = pa.ipc.open_stream(pa.BufferReader(data)).read_all()
+ df = SupersetResultSet.convert_table_to_df(table)
+ for name, data in stmt_data.get("nested_columns_msgpack", {}).items():
+ try:
+ values = deserialize_nested_columns({name: data})[name]
+ if name not in df.columns:
+ raise ValueError("Nested sidecar has no Arrow column")
+ if not isinstance(values, list) or len(values) != len(df):
+ raise ValueError("Nested sidecar does not match Arrow row
count")
+ df[name] = values
+ except (
+ ValueError,
+ TypeError,
+ DecimalException,
+ msgpack.UnpackException,
+ OverflowError,
+ RecursionError,
+ ):
+ # Readers in a rolling deployment may not know newer type tags.
+ logger.warning(
+ "Unable to decode nested SQL column %s; using Arrow
strings",
+ name,
+ exc_info=True,
+ )
+ return df
+
+ columns = [
+ column.get("column_name", column.get("name", ""))
+ for column in stmt_data.get("columns", [])
+ ]
+ return _records_to_dataframe(data, columns)
+
+
+def _records_to_dataframe(
+ records: list[Any],
+ columns: list[Any],
+ dtypes: list[str] | None = None,
+) -> pd.DataFrame:
+ """
+ Build a DataFrame from JSON-style records.
+
+ Values are converted through Arrow, as SELECT results are on the
+ synchronous path, so integer columns with nulls keep ``None`` instead of
+ becoming ``NaN`` floats; mixed or nested values are kept as Python
+ objects. The given columns are kept even when there are no records.
+
+ :param records: Rows as dicts keyed by column name
+ :param columns: Column names, in order
+ :param dtypes: Original pandas dtypes for cached DataFrames
+ :returns: DataFrame of the records
+ """
+ if not columns or not all(isinstance(row, dict) for row in records):
+ return pd.DataFrame(records, columns=columns or None)
Review Comment:
Now that cache hits rebuild a DataFrame, an entry written before this change
has no `columns`/`dtypes`, so it lands on this plain `pd.DataFrame(records,
columns=None)` inference path. For a cached column like `[{"id":
1152921504606846977}, {"id": None}]` pandas picks float64, so the id comes back
as `1152921504606846976` (and `None` becomes `NaN`) until the entry expires, on
both `execute()` and `execute_async().get_result()`. Before this change those
entries were returned as the raw records, so the value was exact. Should legacy
records without `columns` go through the same Arrow conversion in `to_series`
(inferring the column names from the record keys) so nullable large integers
keep their value? Relatedly, the legacy-cache test supplies `columns`, which
the old writer never stored, so it doesn't exercise this path.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]