Skip to content

Dataframe.merge loses data when there are more than 128 partitions #12427

Closed

Description

@hebian1994

Describe the issue:

I made a demo project that reproduces the silent row drop issue with left merge. Feel free to check it out. Thanks!
The issue occurs when the local cluster uses more than 128 partitions. Thanks!

Minimal Complete Verifiable Example:

Image Image

Anything else we need to know?:

Environment:

dask[dataframe,distributed]>=2024.1.0
pandas>=2.0.0
pyarrow>=14.0.0
OS : WINDOWS

Suggested fixes:

Primary (dask): In create_assign_index_merge_transfer() (and similar shuffle transfer paths), if the join key selection is a single-column DataFrame, squeeze to a Series before partitioning_index(), so hashing matches on="POL_ID" semantics.

index = _select_columns_or_index(df, index)
if isinstance(index, pd.DataFrame) and index.shape[1] == 1:
index = index.iloc[:, 0]
Primary (dask): In partitioning_index(), do not use int8 when npartitions > 128 (e.g. use int16 or always int32 for the partition column), so bucket 128 is not stored as -128.

def partitioning_index(df, npartitions, cast_dtype=None):
    """
    Computes a deterministic index mapping each record to a partition.

    Identical rows are mapped to the same partition.

    Parameters
    ----------
    df : DataFrame/Series/Index
    npartitions : int
        The number of partitions to group into.
    cast_dtype : dtype, optional
        The dtype to cast to to avoid nullability issues

    Returns
    -------
    partitions : ndarray
        An array of int64 values mapping each record to a partition.
    """
    if cast_dtype is not None:
        # Fixme: astype raises with strings in numeric columns, but raising
        # here might be very noisy
        df = df.astype(cast_dtype, errors="ignore")
    # print(f'df: {df}')
    res = hash_object_dispatch(df, index=False) % int(npartitions)
    # print(f'res: {res}')
    # Note: Use a signed integer since pandas is more efficient at handling
    # this since there is not always a fastpath for uints
    # type_target = np.min_scalar_type(-(npartitions - 1))
    # print(f'type_target: {type_target}')
    # res2 = res.astype(type_target)
    # print(f'res2: {res2}')
    # return res2
    if npartitions <= np.iinfo(np.int8).max + 1:  # 129 > 128
        dtype = np.int8
    elif npartitions <= np.iinfo(np.int16).max + 1:
        dtype = np.int16
    else:
        dtype = np.int32
    return res.astype(dtype)

Defense in depth (distributed): In split_by_worker(), avoid silently dropping rows when __hash_partition does not match worker_for.index (normalize partition ids and/or warn/raise instead of how="inner" data loss).

Tests to add:

partitioning_index(Series) == partitioning_index(single_col_DataFrame) for string keys
E2E: left.merge(..., shuffle_method="p2p") with npartitions=129 preserves all left rows, including left-only keys hashing to bucket 128

Related code paths:

dask/dataframe/dask_expr/_merge.py — HashJoinP2P._layer(), create_assign_index_merge_transfer()
dask/dataframe/dask_expr/_shuffle.py — _select_columns_or_index()
dask/dataframe/shuffle.py — partitioning_index()
distributed/shuffle/_shuffle.py — split_by_worker()
distributed/shuffle/_merge.py — merge_unpack()

Activity

  1. added
    needs triage
    on May 29, 2026
  2. crusaderky commented on May 29, 2026

    @crusaderky
    Collaborator

    Could you come up with a shorter reproducer?
    Also, does the issue disappear if you don't use LocalCluster (thus switch from p2p to disk shuffle)? What happens if you force shuffle=tasks?

  3. changed the title [-]When a localcluster has more than 128 partitions, merging causes data loss without any warning. Caused by partitioning_index.[/-] [+]`Dataframe.merge` loses data when there are more than 128 partitions[/+] on May 29, 2026
  4. hebian1994 commented on May 29, 2026

    @hebian1994
    ContributorAuthor

    @crusaderky

    i create a short demo code , thanks

    """Reproduces on dask 2026.3.0 + distributed 2026.3.0, LocalCluster."""
    
    import numpy as np
    import pandas as pd
    import dask.dataframe as dd
    from dask.dataframe.dispatch import hash_object_dispatch
    from dask.distributed import Client, LocalCluster
    
    PROBE = "F905535765"
    N = 129
    
    
    def vanilla_partitioning_index(df, npartitions):
        """Upstream 2026.3.0 before fix."""
        res = hash_object_dispatch(df, index=False) % int(npartitions)
        return res.astype(np.min_scalar_type(-(npartitions - 1)))
    
    
    # Part A: Series vs DataFrame hash mismatch
    s_bucket = int(vanilla_partitioning_index(pd.Series([PROBE]), N)[0])
    d_bucket = int(vanilla_partitioning_index(pd.DataFrame({"POL_ID": [PROBE]}), N)[0])
    assert s_bucket != d_bucket  # 9 vs -128
    
    
    # Part B: silent row loss on left merge
    rng = np.random.default_rng(42)
    
    def random_pol_ids(n, exclude):
        out = []
        while len(out) < n:
            cand = f"F{rng.integers(0, 10**9):09d}"
            if cand not in exclude:
                out.append(cand)
        return out
    
    n_rows = N * 200
    left_fill = random_pol_ids(n_rows - 1, {PROBE})
    right_fill = random_pol_ids(n_rows, set(left_fill))
    
    left_pdf = pd.DataFrame({"POL_ID": left_fill + [PROBE], "left_val": range(n_rows)})
    right_pdf = pd.DataFrame({"POL_ID": right_fill, "right_val": range(n_rows)})
    
    with LocalCluster(n_workers=4, threads_per_worker=1, processes=True) as cluster:
        with Client(cluster) as client:
            left = dd.from_pandas(left_pdf, npartitions=2)
            right = dd.from_pandas(right_pdf, npartitions=N)
            
            print(f"left.len: {len(left)}")
            print(f"right.len: {len(right)}")
            merged = left.merge(right, on="POL_ID", how="left", shuffle_method="p2p")
            print(f"merged.len: {len(merged)}")
    
            n_left = int(left.map_partitions(len).sum().compute())
            n_merged = int(merged.map_partitions(len).sum().compute())
            n_probe = int((merged.POL_ID == PROBE).sum().compute())
    
            assert n_merged == n_left, (n_left, n_merged)
            assert n_probe == 1
    Image

    switch from p2p to disk shuffle: will report error : OverflowError: Python integer 129 out of bounds for int8

    Image
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

    dataframeneeds triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions