superset icon indicating copy to clipboard operation
superset copied to clipboard

fix(csv): chart_data_to_dataframe fails on hierarchical temporal columns and missing indexnames

Open ayushbuilds-code opened this issue 5 days ago • 0 comments

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:

  1. KeyError when temporal columns have hierarchical (multi-level) column names: When a chart has hierarchical column headers (e.g. pivot tables or grouped dimensions/metrics where colnames is a list of tuples/lists like [['Group', 'ds'], ['Metrics', 'val']]), chart_data_to_dataframe attempts to cast temporal columns before assigning df.columns to a MultiIndex:

    df[result["result"][0]["colnames"][i]] = df[
        result["result"][0]["colnames"][i]
    ].astype("datetime64[ms]")
    

    At that point, df was created from result["result"][0]["data"] (which contains flattened keys). Indexing df by a list/tuple raises KeyError: "['Group'] not in index". Because this is wrapped in a broad try...except BaseException: logger.error(err) that encloses the whole loop, the exception causes datetime conversion to immediately abort for all remaining temporal columns. Assigning df.columns = MultiIndex.from_tuples(...) first allows df[df.columns[i]] to address the column correctly by index.

  2. Uncaught KeyError when indexnames is 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 unhandled KeyError: 'indexnames'. It should be guarded with .get("indexnames").

  3. Global side effect leak (pd.set_option("display.float_format", ...)): chart_data_to_dataframe executes:

    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], missing indexnames uses the default RangeIndex without crashing, and per-column datetime conversion errors are isolated rather than aborting the entire loop.
  • Actual: KeyError is raised on hierarchical column indexing, aborting temporal conversion for all columns; and missing indexnames crashes with unhandled KeyError.

Environment

  • Superset version: master branch
  • Python version: 3.10+
  • Pandas version: 2.x+

ayushbuilds-code avatar Nov 29 '26 19:11 ayushbuilds-code