Skip to content

P2P shuffling - ArrowInvalid: These dictionaries cannot be combined. The unified dictionary requires a larger index type. #8489

Open

Description

@hidemire

Describe the issue:

During P2P shuffling, the error ArrowInvalid: These dictionaries cannot be combined. The unified dictionary requires a larger index type. occurs.

Minimal Complete Verifiable Example:

To reproduce the error, we created a repository containing the dataset, code to reproduce the error, and a docker-compose file to start the dask cluster and dask-notebook.

How to reproduce the bug

To start containers, run the following command:

docker compose up

In the logs of the notebook container, there will be a link to the notebook of the next format:

http://127.0.0.1:8888/lab?token=c5ff9594e94ae9556be22c1c385152d8b30e0b11ae7b0689

Two notebooks will be available in JupyterLab, distributed.ipynb and local-cluster.ipynb.

An example of code that throws an error:

import dask.dataframe as dd

df = dd.read_parquet('/data/test_dataset.parquet')

def _calculate_time(df):
    df = df.sort_values('sd')
    df['time_diff'] = (df['sd'].diff().dt.total_seconds())
    return df

df = (
    df.groupby(['date', 'fn', 'a', 'wa', 'wp'], observed=True)
    .apply(_calculate_time, meta=_calculate_time(df._meta))
    .reset_index(drop=True)
)

df.groupby(['a'], observed=True).count().compute()

Anything else we need to know?:

The dataset for which this error occurs:
#   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   date    5 non-null      datetime64[us]
 1   fn      5 non-null      category      
 2   a       5 non-null      category      
 3   st      5 non-null      datetime64[ns]
 4   pc      5 non-null      category      
 5   sd      5 non-null      datetime64[ns]
 6   it      0 non-null      category      
 7   ps      5 non-null      category      
 8   ss      5 non-null      category      
 9   lb      5 non-null      category      
 10  ri      5 non-null      category      
 11  watc    5 non-null      category      
 12  wat     5 non-null      category      
 13  wa      5 non-null      category      
 14  wp      5 non-null      category  
pyarrow.Table
date: timestamp[us]
fn: dictionary<values=string, indices=int32, ordered=0>
a: dictionary<values=string, indices=int32, ordered=0>
st: timestamp[ns]
pc: dictionary<values=string, indices=int32, ordered=0>
sd: timestamp[ns]
it: dictionary<values=string, indices=int32, ordered=0>
ps: dictionary<values=string, indices=int32, ordered=0>
ss: dictionary<values=string, indices=int32, ordered=0>
lb: dictionary<values=string, indices=int32, ordered=0>
ri: dictionary<values=string, indices=int32, ordered=0>
watc: dictionary<values=string, indices=int32, ordered=0>
wat: dictionary<values=string, indices=int32, ordered=0>
wa: dictionary<values=string, indices=int32, ordered=0>
wp: dictionary<values=string, indices=int32, ordered=0>

The error resolves when changing the type of some fields to str before groupby:

df['ps'] = df['ps'].astype(str)
df['ss'] = df['ss'].astype(str)
df['lb'] = df['lb'].astype(str)
df['ri'] = df['ri'].astype(str)

We suspect that during P2P shuffling, the initial index size (int32 as seen in pyarrow.Table) for the dictionary is not used.
Therefore, it seems to us that the error occurs during combining a dictionary with int8 and int16 indexes.

Stacktrace can be viewed here distributed.ipynb and here local-cluster.ipynb

Feel free to ask any additional questions.

Environment:

  • Dask version: 2024.1.0
  • Python version: 3.10.12.final.0
  • Operating System: macOS Sonoma 14.2.1
  • Install method (conda, pip, source): docker

Activity

  1. added
    bug
    and removed on Feb 10, 2025
  2. mikeoconnor0308 commented on Jul 4, 2025

    @mikeoconnor0308

    I encounted this too. In my case, it was the following:

    • A parquet dataset spread across many files used categories, but without global category values being stored. The total cardinality of a given category was a lot higher than any individual file would indicate.
    • When read in, the dataframes end up using small index types, as noted.
    • On merge/shuffle, we see the error above.

    My fix was the following, which avoids casting all the data to str by determining the global values.

    def make_global_categories(ddf: dd.DataFrame) -> dd.DataFrame:
        """
        Recast all categorical columns in a Dask DataFrame to have global categories.
    
        This is important when one needs to merge Dask DataFrames with categorical columns,
        where the categories may not have been consistent across partitions, and can lead to errors.
    
        We do this by computing the unique values across all partitions and then updating the dataframe category
        values to ensure they are consistent across all partitions.
    
        Memory consumption could be high if the unique values are exceedingly large.
        """
    
        categorical_columns = [col for col in ddf.columns if ddf[col].dtype.name == "category"]
        delayed_uniques = {col: ddf[col].astype(str).unique() for col in categorical_columns}
        # Compute these uniques in parallel
        computed_uniques = dd.compute(*delayed_uniques.values())
        # Map back to column names
        column_to_unique = {
            col: pd.CategoricalDtype(sorted(unique))
            for col, unique in zip(delayed_uniques.keys(), computed_uniques)
        }
    
        def recast(df, column_dtypes):
            for column, dtype in column_dtypes.items():
                df[column] = pd.Series(df[column], dtype=dtype)
            return df
    
        return ddf.map_partitions(recast, column_to_unique, meta=ddf._meta)

    The following test demonstrates the crux of the behaviour (which at large scale leads to the index type problem):

    @pytest.fixture
    def ddf_with_categoricals(tmp_path: Path) -> dd.DataFrame:
        """
        Fixture for a Dask DataFrame with categorical columns with inconsistent categories.
        Uses a Parquet round-trip to get the state of each partition having different categories.
        """
        pdf1 = pd.DataFrame({"cat": pd.Categorical(["a", "b"]), "val": [1, 2]})
        pdf2 = pd.DataFrame({"cat": pd.Categorical(["b", "c"]), "val": [3, 4]})
    
        schema = pa.schema([pa.field("cat", pa.dictionary(pa.int32(), pa.string())), pa.field("val", pa.int64())])
        pdf1.to_parquet(tmp_path / "pdf1.parquet", schema=schema)
        pdf2.to_parquet(tmp_path / "pdf2.parquet", schema=schema)
        ddf = dd.read_parquet(tmp_path, schema=schema)
        return ddf
    
    
    def test_make_global_categories_recasts(ddf_with_categoricals: dd.DataFrame) -> None:
        """
        Test that make_global_categories recasts all categorical columns to have global categories.
        This ensures that all partitions share the same set of categories, which is required for safe merges.
        """
        ddf = ddf_with_categoricals
        # Before: categories are not global
        categories_before = [set(ddf.get_partition(i).compute()["cat"].cat.categories) for i in range(ddf.npartitions)]
        assert categories_before[0] != categories_before[1]
        ddf_global = make_global_categories(ddf)
        df1 = ddf_global.get_partition(0).compute()
        df2 = ddf_global.get_partition(1).compute()
        categories_after = [set(df1["cat"].cat.categories), set(df2["cat"].cat.categories)]
        # After: categories are global and equal
        assert categories_after[0] == categories_after[1]
        assert categories_after[0] == {"a", "b", "c"}

    I'm not sure if it's pyarrow or pandas that's miscasting the category index, I'm guessing pandas. Would be nice if that could be set to avoid this situation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bughelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions