fix(csv): chart_data_to_dataframe fails on hierarchical temporal columns and missing indexnames
Bug description
In superset/utils/csv.py, the chart_data_to_dataframe function converts chart-data JSON into a pandas DataFrame representation used for email and Slack alert/report notifications.
There are three related defects in chart_data_to_dataframe:
-
KeyErrorwhen temporal columns have hierarchical (multi-level) column names: When a chart has hierarchical column headers (e.g. pivot tables or grouped dimensions/metrics wherecolnamesis a list of tuples/lists like[['Group', 'ds'], ['Metrics', 'val']]),chart_data_to_dataframeattempts to cast temporal columns before assigningdf.columnsto aMultiIndex:df[result["result"][0]["colnames"][i]] = df[ result["result"][0]["colnames"][i] ].astype("datetime64[ms]")At that point,
dfwas created fromresult["result"][0]["data"](which contains flattened keys). Indexingdfby a list/tuple raisesKeyError: "['Group'] not in index". Because this is wrapped in a broadtry...except BaseException: logger.error(err)that encloses the whole loop, the exception causes datetime conversion to immediately abort for all remaining temporal columns. Assigningdf.columns = MultiIndex.from_tuples(...)first allowsdf[df.columns[i]]to address the column correctly by index. -
Uncaught
KeyErrorwhenindexnamesis omitted:result["result"][0]["indexnames"]is accessed via direct key lookup:df.index = pd.MultiIndex.from_tuples( tuple(indexname) if isinstance(indexname, list) else (indexname,) for indexname in result["result"][0]["indexnames"] )If a query result payload does not include
indexnames(e.g. from non-pivot queries or custom query contexts), this crashes with an unhandledKeyError: 'indexnames'. It should be guarded with.get("indexnames"). -
Global side effect leak (
pd.set_option("display.float_format", ...)):chart_data_to_dataframeexecutes:pd.set_option("display.float_format", lambda x: str(x))This modifies pandas' global process configuration for the entire Python worker process and is never reset.
How to reproduce the bug
Call chart_data_to_dataframe with a chart-data JSON payload that has hierarchical column headers and a TEMPORAL column type:
import json
from superset.utils.csv import chart_data_to_dataframe
from superset.utils.core import GenericDataType
payload = json.dumps({
"result": [{
"data": [{"hire_date": "2024-01-01", "salary": 50000}],
"colnames": [["Info", "hire_date"], ["Metrics", "salary"]],
"coltypes": [GenericDataType.TEMPORAL, GenericDataType.NUMERIC],
"indexnames": [0]
}]
}).encode("utf-8")
df = chart_data_to_dataframe(payload)
# KeyError: "['Info'] not in index" logged, hire_date remains unparsed string
assert df[("Info", "hire_date")].dtype == "datetime64[ms]" # FAILS
Expected vs actual behavior
- Expected: Hierarchical temporal columns are cast to
datetime64[ms], missingindexnamesuses the default RangeIndex without crashing, and per-column datetime conversion errors are isolated rather than aborting the entire loop. - Actual:
KeyErroris raised on hierarchical column indexing, aborting temporal conversion for all columns; and missingindexnamescrashes with unhandledKeyError.
Environment
- Superset version: master branch
- Python version: 3.10+
- Pandas version: 2.x+