Skip to content

[Data] Fix disk shuffle directory leaks on mid-map cancellation - #68522

Open
Yin-1022 wants to merge 3 commits into
ray-project:masterfrom
Yin-1022:fix-disk-shuffle-directory-leak
Open

Yin-1022 wants to merge 3 commits into
ray-project:masterfrom
Yin-1022:fix-disk-shuffle-directory-leak

Conversation

@Yin-1022

Copy link
Copy Markdown
Contributor

Description

This PR addresses the remaining disk shuffle directory leak reported in #67958.

Following #67143, ShuffleFileServer actors are now owned and cleaned up by DiskHashShuffleRegroupOp.
However, disk shuffle directories can still be leaked when a map task is cancelled before returning its shuffle handle.

The map task creates its local shuffle directory before partitioning the input data. If cancellation occurs during this stage, the regroup operator never receives the handle and therefore has no record of the corresponding shuffle directory in _file_servers.

As a result, the existing teardown logic does not clean up these directories, allowing them to accumulate across repeated cancellations.

Changes

  • Preserve the shuffle ID at physical planning time, independently of completed map-task handles.
  • Collect planned shuffle IDs in DiskHashShuffleRegroupOp during initialization.
  • Extend teardown to clean up directories associated with planned shuffle IDs on all currently alive nodes, including nodes that have not returned any shuffle handles.
  • Add unit and integration regression tests covering cleanup without completed mapper handles and cancellation during map-side partitioning.

Before / After Comparison

The following results were obtained using a single-node reproduction with three consecutive mid-map cancellations.
Both versions include the actor ownership fix introduced in #67143, and no leaked ShuffleFileServer actors were observed in either version.

Scenario Before (leftover directories) After (leftover directories)
Normal execution 0 0
Cancellation round 1 1 0
Cancellation round 2 2 0
Cancellation round 3 3 0
After driver reconnection 3 0

Without the fix, shuffle directories accumulate across repeated cancellations and persist after driver reconnection.
With the fix, no leftover directories were observed.

Red/Green tests

Added two regression tests:

  • test_disk_shuffle_teardown_cleans_nodes_without_mapper_handles
  • test_disk_shuffle_mid_map_cancel_cleans_directories

The integration test uses a gated partition function to trigger cancellation after the map directory has been created but before the mapper returns its shuffle handle.

Red — original cleanup behavior:

CANCEL_RESULT gate=True interrupted=True
leftover=['.../ray_shuffle_disk_3fe9a36f6badfc62_map']

AssertionError: shuffle directories leaked

Green — with the fix:

test_disk_shuffle_teardown_cleans_nodes_without_mapper_handles PASSED
test_disk_shuffle_mid_map_cancel_cleans_directories PASSED

Additional validation:

  • All five disk shuffle operator fusion tests introduced in [Data] Fuse shuffle map with map op #68433 passed.
  • Hash Shuffle V2 test suite: 133 passed, 1 failed. The existing test_disk_shuffle_leaves_no_file_server_actors test could not query actor states because the local Dashboard State API was unavailable.

Related issues

Closes #67958. Follow-up to #67143.

Additional information

Cleanup intentionally targets all currently alive nodes for each planned shuffle ID, since cancelled mappers may create directories without returning handles. This trades additional cleanup RPCs for coverage of incomplete map tasks.

Runtime validation was performed on a single-node cluster, while the unit test covers multi-node cleanup target selection.

@Yin-1022
Yin-1022 requested a review from a team as a code owner November 24, 2026 17:19

@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 disk shuffle directories are properly cleaned up when mappers are cancelled before returning handles. It tracks planned shuffle IDs on the driver and cleans them up across all alive nodes during teardown. The feedback suggests removing a hardcoded /tmp directory in the new tests to ensure Windows compatibility, and clearing _planned_shuffle_ids during teardown to ensure idempotency.

"""
)

with tempfile.TemporaryDirectory(prefix="rds_", dir="/tmp") as tmp_dir:

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.

high

Hardcoding dir="/tmp" in tempfile.TemporaryDirectory will cause test failures on Windows environments, as /tmp is not a standard directory on Windows. Since Ray supports Windows, we should omit the dir argument so it defaults to the OS-specific temporary directory.

Suggested change
with tempfile.TemporaryDirectory(prefix="rds_", dir="/tmp") as tmp_dir:
with tempfile.TemporaryDirectory(prefix="rds_") as tmp_dir:

@Yin-1022 Yin-1022 Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The short /tmp path is intentional to avoid the Unix domain socket path length limit during Ray initialization.

Since the test also relies on POSIX SIGINT cancellation semantics, so simply removing dir="/tmp" would not make it Windows-compatible.
I've restricted it to Linux and documented the reason for using a short temporary path.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Nov 24, 2026
@owenowenisme owenowenisme self-assigned this Nov 25, 2026
for shuffle_id in self._planned_shuffle_ids:
shuffle_nodes.add((shuffle_id, node_id))

teardown_disk_shuffle(shuffle_nodes)

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.

Can this cleanup run before a cancelled mapper finishes mkdir? _ClosingIterator shuts down with force=False, so it doesn’t wait for the mapper to exit. In a local test that delayed mkdir until after teardown returned, the mapper then created an empty shuffle directory that was still there four seconds later.

The new test sends SIGINT after the directory already exists. Could we also cover cancellation while mkdir is still in progress?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for catching this race problem!

I've reproduced the issue by injecting a delayed mkdir that completes after cancellation is requested.

The updated implementation captures streaming task completion refs before cancellation and passes them to the node-local cleanup tasks. Cleanup now waits for those refs before removing the shuffle directories without requiring the driver to synchronously wait for task termination. This also covers fused operators that participate in multiple disk shuffles.

I've extended the regression test to cover cancellation both after and during mkdir, and verified that the new case fails with leaked directories before the fix and passes afterward.

@rayo5o rayo5o 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.

Both new tests fail on the merge base 32f51e2 (the integration test leaves one ray_shuffle_disk_<id>_map directory) and pass on 5d6a8da. Reverting either half on its own, the planner no longer setting _disk_shuffle_id or teardown skipping the alive-node loop, makes both fail again, so each part is covered.

I also cancelled at the same point on two paths the test doesn't use:

  • map_batches before repartition, so the writer gets fused with the upstream map
  • join, which has two map ops and two shuffle IDs

The merge base leaves one map directory in each case; this PR leaves none.

Since the shuffle ID is now kept from planning time, I checked that two overlapping iter_batches over the same Dataset, and two materialize() calls in a row, each get their own ID. Both runs return all 4,000 rows and nothing is left on disk, so one run's teardown can't remove the other's directory.

One thing outside this PR: if the driver is killed with SIGKILL during the map, the _map directory stays on both the merge base and this PR, also after ray stop, since teardown never runs. Not asking for it here, just mentioning it in case #67958 was meant to include that case.

All of this was on a single node (WSL, 4 CPUs, pyarrow 25.0.1). I didn't try a real multi-node cluster.

@Yin-1022

Copy link
Copy Markdown
Contributor Author

Both new tests fail on the merge base 32f51e2 (the integration test leaves one ray_shuffle_disk_<id>_map directory) and pass on 5d6a8da. Reverting either half on its own, the planner no longer setting _disk_shuffle_id or teardown skipping the alive-node loop, makes both fail again, so each part is covered.

I also cancelled at the same point on two paths the test doesn't use:

  • map_batches before repartition, so the writer gets fused with the upstream map
  • join, which has two map ops and two shuffle IDs

The merge base leaves one map directory in each case; this PR leaves none.

Since the shuffle ID is now kept from planning time, I checked that two overlapping iter_batches over the same Dataset, and two materialize() calls in a row, each get their own ID. Both runs return all 4,000 rows and nothing is left on disk, so one run's teardown can't remove the other's directory.

One thing outside this PR: if the driver is killed with SIGKILL during the map, the _map directory stays on both the merge base and this PR, also after ray stop, since teardown never runs. Not asking for it here, just mentioning it in case #67958 was meant to include that case.

All of this was on a single node (WSL, 4 CPUs, pyarrow 25.0.1). I didn't try a real multi-node cluster.

Thanks for the thorough testing, especially the independent red/green validation, checking each part of the fix separately, and covering the fused map, join, and overlapping execution cases! The shuffle ID isolation checks are particularly helpful.

I agree that the SIGKILL case is a separate lifecycle issue, since the driver's teardown never runs.
I'd prefer to keep that outside the scope of this PR.

I've also addressed the cancellation ordering race raised by Efutrrionpy in the latest commit, with an additional regression test covering delayed mkdir completion after cancellation.

@rayo5o rayo5o 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.

Re-ran my first-pass checks on 8693924: cancelling on the plain, fused and join paths and the two overlapping runs still leave nothing behind. The five cleanup tests pass here and all fail on the merge base, and they run all 36 changed lines. Agreed on keeping SIGKILL separate.

One trade-off from the new wait, inline below.


# Completion refs may contain cancellation errors. Wait for readiness
# instead of fetching their values.
if completion_refs:

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.

One case gets worse than on 5d6a8da. If a cancelled mapper stays inside a call that can't be interrupted for longer than the driver's 5 s wait, and the driver exits right after the cancel, this cleanup task is still blocked here when the job ends and gets killed with it, so the _map directory stays.

Repro on a ray start cluster: the partition fn sleeps 8 s in libc.sleep (the KeyboardInterrupt is only handled once it returns), the driver cancels during the map and exits, and a new driver looks 20 s later. 8693924 leaves the directory in 3 of 3 runs, 5d6a8da in 0 of 2 (the merge base leaves it too). With a 3 s stall, or if the driver stays up 15 s, 8693924 cleans up fine. I don't know how often a mapper takes over 5 s to notice a cancel in practice; a big block in the partition step might.

Removing once before the wait and again after it fixed this here:

    if completion_refs:
        shutil.rmtree(map_dir, ignore_errors=True)
        shutil.rmtree(reduce_dir, ignore_errors=True)
        ray.wait(
            list(completion_refs),
            num_returns=len(completion_refs),
            fetch_local=False,
        )

    shutil.rmtree(map_dir, ignore_errors=True)
    shutil.rmtree(reduce_dir, ignore_errors=True)

With that, the 8 s case leaves nothing (2 of 2), and both mid_map_cancel cases including during-mkdir still pass. test_disk_shuffle_cleanup_waits_for_task_completion then fails, since it asserts the directories still exist when ray.wait is called; it would need to check they're gone afterwards instead.

This branch has not been deployed

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

Labels

community-contribution Contributed by the community data Ray Data-related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] Disk Shuffle V2 leaks detached ShuffleFileServer actors and temporary directories on mid-map cancellation

4 participants