Skip to content

[Data] Preserve input order for seeded random shuffles on the disk shuffle - #68417

Merged
richardliaw merged 3 commits into
ray-project:masterfrom
rayhhome:random-shuffle-seed-preserve-order
Nov 21, 2026
Merged

richardliaw merged 3 commits into
ray-project:masterfrom
rayhhome:random-shuffle-seed-preserve-order

Conversation

@rayhhome

Copy link
Copy Markdown
Contributor

Summary

random_shuffle(seed=...) on the disk-based shuffle v2 could return a different order across runs. The plan now requires preserve_order for a seeded shuffle on that path, the same mechanism zip uses, so each input block always gets the same map task index and therefore the same seed.

Before

Two things must hold for a seeded shuffle to be repeatable: every block must get the same seed, and partitions must come out in the same order. #68319 fixed the second (the reduce emits partitions in id order and sorts mapper handles by map id). The first still varied: RandomShufflePartitioner seeds a block from (seed, map_task_index, block_index), and the disk writer's map task index is handed out in input arrival order because it does not fuse with the read. When read tasks finish out of order, a block gets a different seed. This is the flake behind test_random_shuffle[shuffle_v2_disk] (postmerge 21143, failed once, passed on retry). The legacy shuffle avoids it only because its upstream map fuses into the shuffle map stage.

After

LogicalPlan.require_preserve_order() returns True for a RandomShuffle with a user seed when the context selects SHUFFLE_V2 with use_disk_based_hash_shuffle. Dataset._start_execution already turns that into preserve_order=True on the executor, so upstream operators emit in task-index order and each block's map task index is fixed. Unseeded shuffles and the legacy paths are untouched.

flowchart TD
    subgraph Before
        subgraph BP[Logical planning]
            B1[require_preserve_order: Zip only]
        end
        subgraph BE[Execution]
            B2[Read emits in completion order] --> B3[Map: map_id = arrival order, seed = f seed, map_id]
            B3 --> B4[Reduce: partitions in id order, since #68319]
        end
    end
    subgraph After
        subgraph AP[Logical planning]
            A1[require_preserve_order: Zip, or seeded RandomShuffle on disk v2]
        end
        subgraph AE[Execution]
            A2[Read emits in task-index order] --> A3[Map: map_id = input index, seed = f seed, map_id]
            A3 --> A4[Reduce: partitions in id order, since #68319]
        end
    end
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class A1,A2,A3 changed
Loading

Subsystems

Logical planning (the change), shuffle / aggregation (the affected path).

Testing

  • test_optimize.py::test_seeded_disk_shuffle_requires_preserve_order: the hook fires only for a seeded shuffle under disk v2.
  • test_random_e2e.py::test_seeded_random_shuffle_ignores_arrival_order: makes the last read block finish first and asserts the seeded output matches the in-order run, under every shuffle strategy. Fails on master for shuffle_v2_disk.
pytest python/ray/data/tests/test_optimize.py python/ray/data/tests/test_random_e2e.py \
  -k "preserve_order or ignores_arrival_order or (test_random_shuffle and shuffle_v2_disk)"
14 passed

Notes

  • preserve_order=True disables Ray Data lineage reconstruction for that execution, with the existing warning. A seeded shuffle already promises a reproducible order, so this is the right trade.
  • Not covered, as for zip today: operators that read the flag at plan time, namely the v2 hash-shuffle reducers (join, groupby, keyed repartition) and parallel file listing. A seeded shuffle directly after one of those still follows arrival order unless execution_options.preserve_order is set on the context before execution. No existing test places a seeded shuffle after those.
  • Not a duplicate: [Data] Emit Seeded Disk Random Shuffle Partitions in Order #68319 addressed reduce-side partition order; no open PR touches the map-side seed. Written with AI assistance.

🤖 Generated with Claude Code

…uffle v2

The disk shuffle v2 map derives each block's seed from its map task index,
which is handed out in input arrival order. When read tasks finish out of
order a block gets a different seed, so random_shuffle(seed=...) returned
different orders across runs (flaky test_random_shuffle[shuffle_v2_disk]).
The legacy shuffle is immune only because its upstream map fuses into the
shuffle map stage, so block i is always map task i.

Have the logical plan require preserve_order, as it does for zip, when it
contains a user-seeded RandomShuffle that the context routes to the disk
shuffle v2. Ordered upstream output pins every block to one map task index.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
@rayhhome rayhhome added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Nov 20, 2026
@rayhhome
rayhhome requested a balanced review from Copilot November 20, 2026 22:23
@rayhhome
rayhhome marked this pull request as ready for review November 20, 2026 22:23
@rayhhome
rayhhome requested a review from a team as a code owner November 20, 2026 22:23

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request ensures that seeded random shuffles using disk-based hash shuffle v2 preserve input arrival order to maintain deterministic outputs. It updates the logical plan's order preservation requirements and adds corresponding unit and end-to-end tests. The review feedback suggests two key improvements: adding a defensive check to prevent a potential AttributeError when accessing op.seed_config in the logical plan, and refactoring the end-to-end test helper to safely handle different batch formats and avoid potential indexing errors.

Comment on lines +176 to +178
def finish_last_block_first(batch):
time.sleep(0.2 * (4 - batch["id"][0] // 20))
return batch

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Accessing batch['id'][0] directly can lead to issues:

  1. If batch is a pandas DataFrame, batch['id'] is a pandas Series, and batch['id'][0] performs label-based indexing. If the index is global (e.g., 20 to 39 for the second block), this will raise a KeyError.
  2. If the batch is empty, it will raise an IndexError.

Converting the batch column to a numpy array using np.asarray and checking its length makes this test robust across all batch formats (dict, pandas, arrow) and safe against empty batches.

Suggested change
def finish_last_block_first(batch):
time.sleep(0.2 * (4 - batch["id"][0] // 20))
return batch
def finish_last_block_first(batch):
ids = np.asarray(batch['id'])
if len(ids) > 0:
time.sleep(0.2 * (4 - ids[0] // 20))
return batch

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues were identified for the change to preserve input order in seeded disk-based shuffles.

No open issues 🎉

What changed in this PR

This PR makes seeded random shuffles on Ray Data’s disk-based shuffle v2 repeatable by preserving upstream input order. It complements #68319’s reduce-side ordering fix by stabilizing the map task indices used to seed input blocks.

Changes:

  • Require preserved input order for seeded disk shuffle v2, leaving unseeded and legacy shuffle paths unchanged.
  • Add coverage for the seed and shuffle-configuration conditions.
  • Add a regression test comparing seeded outputs with and without delayed upstream batches.
File Description
python/​ray/​data/​tests/​test_random_e2e.py Tests seeded shuffle consistency when upstream batches are delayed.
python/​ray/​data/​tests/​test_optimize.py Tests when seeded shuffles require preserved order.
python/​ray/​data/​_internal/​logical/​interfaces/​logical_plan.py Requires preserved order for seeded disk shuffle v2 plans.

Review effort: Balanced

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
@richardliaw
richardliaw merged commit d657aa6 into ray-project:master Nov 21, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants