Skip to content

[Core][Bug fix] Trigger local task scheduling after deleting bundle. - #51125

Closed
Catch-Bull wants to merge 8 commits into
ray-project:masterfrom
Catch-Bull:fix_pg_leaky
Closed

Catch-Bull wants to merge 8 commits into
ray-project:masterfrom
Catch-Bull:fix_pg_leaky

Conversation

@Catch-Bull

Copy link
Copy Markdown
Contributor

Why are these changes needed?

details: #51124

Related issue number

Closes #51124

Checks

@Catch-Bull
Catch-Bull requested a review from jjyao March 6, 2025 11:24
@Catch-Bull Catch-Bull added the go add ONLY when ready to merge, run all tests label Mar 6, 2025
@jcotant1 jcotant1 added the core Issues that should be addressed in Ray Core label Mar 6, 2025

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

Thanks for the fix! I have a general comment.

If I understand correctly, the issue happens because of a race condition. When Ray tries to release the placement group bundles, it first cancels the associated tasks and kills the related workers and then return the bundles assuming there is no allocation to the bundles-to-return. However, it is possible that right after the related workers are killed and before the return happens, another worker get a task that needs the placement group and allocates the resources for the task. This will cause the bundles-to-return again be allocated, breaks the assumption of the return bundle function and thus the check failure.

Regarding the fix proposed in the PR, looks like it covers the most common case of the race condition issue. At the same time, I think it might not cover the case where the ScheduleAndDispatchTasks function got called in a different place other than the DisconnectClient function. And also, blindly disable the task schedule for all tasks will delay the task scheduling that doesn't require the placement group.

Therefore, I’m wondering if a better approach to fully solve the race condition is to implement a locking mechanism for the placement group where after the placement group is locked, no other tasks can allocate resource from it. In this case, we can lock the bundles first and then do the clean up of the tasks/workers to fully avoid the race condition. I think it is also more straightforward and cleaner. What do you think?

@Catch-Bull

Copy link
Copy Markdown
Contributor Author

Thanks for the fix! I have a general comment.

If I understand correctly, the issue happens because of a race condition. When Ray tries to release the placement group bundles, it first cancels the associated tasks and kills the related workers and then return the bundles assuming there is no allocation to the bundles-to-return. However, it is possible that right after the related workers are killed and before the return happens, another worker get a task that needs the placement group and allocates the resources for the task. This will cause the bundles-to-return again be allocated, breaks the assumption of the return bundle function and thus the check failure.

Regarding the fix proposed in the PR, looks like it covers the most common case of the race condition issue. At the same time, I think it might not cover the case where the ScheduleAndDispatchTasks function got called in a different place other than the DisconnectClient function. And also, blindly disable the task schedule for all tasks will delay the task scheduling that doesn't require the placement group.

Therefore, I’m wondering if a better approach to fully solve the race condition is to implement a locking mechanism for the placement group where after the placement group is locked, no other tasks can allocate resource from it. In this case, we can lock the bundles first and then do the clean up of the tasks/workers to fully avoid the race condition. I think it is also more straightforward and cleaner. What do you think?

@MengjinYan It seems that the related timing should be deterministic, and I think there should be no race condition here. The node_manager should be single-threaded. I think the current order of operations in the function HandleCancelResourceReserve is wrong:

  1. First, kill the worker corresponding to the resource;
  2. Immediately attempt to reschedule the task after killing the worker: DestroyWorker -> DisconnectClient and reschedule;
  3. The ray check bundle is not in use;

I think the correct order should be 1 -> 3 -> 2.

At the same time, I also agree that the best practice should be to lock the resources (The current PR may bring additional burdens in subsequent code maintenance.), but it seems that the threading model of the node_manager is not something that can be easily fixed with a simple patch.

@MengjinYan

Copy link
Copy Markdown
Contributor

Thanks for the fix! I have a general comment.
If I understand correctly, the issue happens because of a race condition. When Ray tries to release the placement group bundles, it first cancels the associated tasks and kills the related workers and then return the bundles assuming there is no allocation to the bundles-to-return. However, it is possible that right after the related workers are killed and before the return happens, another worker get a task that needs the placement group and allocates the resources for the task. This will cause the bundles-to-return again be allocated, breaks the assumption of the return bundle function and thus the check failure.
Regarding the fix proposed in the PR, looks like it covers the most common case of the race condition issue. At the same time, I think it might not cover the case where the ScheduleAndDispatchTasks function got called in a different place other than the DisconnectClient function. And also, blindly disable the task schedule for all tasks will delay the task scheduling that doesn't require the placement group.
Therefore, I’m wondering if a better approach to fully solve the race condition is to implement a locking mechanism for the placement group where after the placement group is locked, no other tasks can allocate resource from it. In this case, we can lock the bundles first and then do the clean up of the tasks/workers to fully avoid the race condition. I think it is also more straightforward and cleaner. What do you think?

@MengjinYan It seems that the related timing should be deterministic, and I think there should be no race condition here. The node_manager should be single-threaded. I think the current order of operations in the function HandleCancelResourceReserve is wrong:

  1. First, kill the worker corresponding to the resource;
  2. Immediately attempt to reschedule the task after killing the worker: DestroyWorker -> DisconnectClient and reschedule;
  3. The ray check bundle is not in use;

I think the correct order should be 1 -> 3 -> 2.

At the same time, I also agree that the best practice should be to lock the resources (The current PR may bring additional burdens in subsequent code maintenance.), but it seems that the threading model of the node_manager is not something that can be easily fixed with a simple patch.

You are right. The node_manager should be single threaded so there's no race condition. And agree that the mechanism of locking the bundle could be complex to implement.

Also agree upon the idea of the current operation sequence can be improved and current PR can bring some maintenance burden.

I discussed with @jjyao on this and we think there might a better way for the fix to reduce potential maintenance burden with the current idea:

  • Today the sequence of operations happens this way because the ScheduleAndDispatchTasks() is called inside of the DisconnectClient(). There can be cases where after DisconnectClient() is called, there are still cleanup work needs to be done (our case is an example).
  • And the function name "DisconnectClient" also doesn't imply the scheduling of the tasks.
  • So a better way could be to remove the ScheduleAndDispatchTasks() function call from the DisconnectClient() and have a separate function call as a wrapper to do both.
  • And in our case, we can call ScheduleAndDispatch() separately after the bundle is returned.

I checked the code briefly, the DisconnectClient() mainly only used in the node_manager.cc file and it shouldn't be a very complex change. What do you think?

@Catch-Bull
Catch-Bull force-pushed the fix_pg_leaky branch 2 times, most recently from bdb1d69 to 24ab587 Compare March 18, 2025 08:20
@Catch-Bull

Copy link
Copy Markdown
Contributor Author

@MengjinYan Could you review it again?

@Catch-Bull

Copy link
Copy Markdown
Contributor Author

@MengjinYan @jjyao Could you take a look at this pr

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

Thanks for the effort!!

Comment thread src/ray/raylet/node_manager.h Resolved
Comment thread src/ray/raylet/node_manager.cc Resolved
Comment thread src/ray/raylet/node_manager.cc Resolved

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 you add comments describing the behavior we are testing (not scheduling another task/actor in the progress of removing a placement group) with the scenario?

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.

done.

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.

I think the test can be simplified by not using a detached placement group and detached actor. We can directly creating 2 actors waiting on the placement group, wait for a bit for one actor to be alive and there other is waiting on the resources (There is not a specific state as waiting for resources so it is hard to detect and probably wait a bit can be a solution) and then remove the placement group and check whether it can be removed successfully. What do you think?

@Catch-Bull Catch-Bull Mar 31, 2025 •

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.

@MengjinYan It seems that the actor here must be detached. Whether it is a PG is not that important. The key point is that only a detached actor can pass this check for scheduling, then occupy the bundle, and ultimately cause the raylet to crash. I have tried with non-detached actors, and I cannot reproduce this issue.

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.

I was able to reproduce with the following test function:

def test_remove_placement_group_with_actor_waiting_on_resource(ray_start_cluster, capsys):
    import os

    cluster = ray_start_cluster
    cluster.add_node(num_cpus=1)
    cluster.wait_for_nodes()
    ray.init(address=cluster.address, namespace="test")

    pg = ray.util.placement_group(
        [{"CPU": 1}],
    )

    @ray.remote
    class Actor:
        def get_raylet_pid(self):
            return os.getppid()

    actor = Actor.options(
        num_cpus=1.0,
        scheduling_strategy=PlacementGroupSchedulingStrategy(
            placement_group=pg, placement_group_bundle_index=0
        ),
    ).remote()

    ray.get(actor.get_raylet_pid.remote())

    _ = Actor.options(
        num_cpus=1.0,
        scheduling_strategy=PlacementGroupSchedulingStrategy(
            placement_group=pg, placement_group_bundle_index=0
        ),
    ).remote()

    time.sleep(1)
    ray.util.remove_placement_group(pg)
    time.sleep(1)
    
    captured = capsys.readouterr()
    lines = captured.err.strip().split("\n")
    for line in lines:
        assert "Check failed:" not in line

The above failed with the following when it is without the change in this PR:

E           AssertionError: assert 'Check failed:' not in '\x1b[33m(ra...etry again. '
E             'Check failed:' is contained here:
E               (raylet) [2025-03-31 11:22:48,856 C 42464 11099512] (raylet) node_manager.cc:2185:  Check failed: placement_group_resource_manager_->ReturnBundle(bundle_spec) Status not OK: Invalid: Bundle resources are still in use. Retry again. 
E             ?                                                                                              +++++++++++++

I think without the fix, essentially, as long as there are multiple actors waiting on the same bundle and the actors that haven't been scheduled is already in the tasks_to_schedule_ map, when disconnect the client, the actor creation tasks in the tasks_to_schedule_ map will be scheduled on the bundle.

To the point about the check, it's a good point. But, I think the non-detach actor can pass the check as well, as long as the caller is alive. And in our case, the caller from what I understand is the driver process. And when we remove the placement group, the driver process is still alive so the check will pass for us.

I might miss something as well. So let me know your thought about it.

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.

@MengjinYan You are right. It can be reproduced simply by waiting for a few seconds before removed the pg. It seems that there are still some differences between the reproduction paths of detached and non-detached. I have made some modifications to this test case to support testing both lifetimes simultaneously.

@MengjinYan MengjinYan added the @external-author-action-required Alternate tag for PRs where the author doesn't have labeling permission. label Mar 28, 2025
@Catch-Bull

Catch-Bull commented Apr 1, 2025 •

Copy link
Copy Markdown
Contributor Author

@MengjinYan I've updated the code. Please take another look when you have time

@MengjinYan

Copy link
Copy Markdown
Contributor

@MengjinYan I've updated the code. Please take another look when you have time

Thanks for the update! I've also replied on the comment related to the test. Let me know what you think.

@hainesmichaelc hainesmichaelc added the community-contribution Contributed by the community label Apr 4, 2025

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

Overall looks good! Only minor comments.

hejialing.hjl added 8 commits April 11, 2025 15:38
Signed-off-by: hejialing.hjl <[email protected]>
Signed-off-by: hejialing.hjl <[email protected]>
Signed-off-by: hejialing.hjl <[email protected]>
Signed-off-by: hejialing.hjl <[email protected]>
Signed-off-by: hejialing.hjl <[email protected]>
Signed-off-by: hejialing.hjl <[email protected]>
Signed-off-by: hejialing.hjl <[email protected]>
Signed-off-by: hejialing.hjl <[email protected]>
@Catch-Bull

Copy link
Copy Markdown
Contributor Author

@MengjinYan I've updated the code. Please take another look when you have time

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

Looks good! Really appreciate the fixes and patience!!

@MengjinYan

Copy link
Copy Markdown
Contributor

@jjyao The test failure seems to be unrelated dashboard test failures. Wondering if you can help to take a look and merge the PR? Thanks!


# check raylet pass raycheck:
# `RAY_CHECK_OK(placement_group_resource_manager_->ReturnBundle(bundle_spec))`
assert raylet.is_running()

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.

@Catch-Bull after running this test with your fix, I just realized one thing.

Currently with your fix, the second actor will just be waiting inside raylet forever waiting for the removed PG resource. And then I realized that we can have a simpler and better fix: when we delete a bundle during NodeManager::HandleCancelResourceReserve, we should cancel all the tasks that require the PG resource so that later on when we DestroyWorker, even if we do the scheduling again, there is nothing can be scheduled and use the PG resource just released by the DestroyWorker.

If you check the NodeManager::HandleCancelResourceReserve impl, we are kind of already doing that but not fully:

  // to free the acquired pg bundle resources
  // so that pg bundle can be returned.
  local_task_manager_->CancelTasks(
      [&](const std::shared_ptr<internal::Work> &work) {
        const auto bundle_id = work->task.GetTaskSpecification().PlacementGroupBundleId();
        return (bundle_id.first == bundle_spec.PlacementGroupId()) &&
               (work->GetState() == internal::WorkStatus::WAITING_FOR_WORKER);
      },
      rpc::RequestWorkerLeaseReply::SCHEDULING_CANCELLED_PLACEMENT_GROUP_REMOVED,
      absl::StrCat("Required placement group ",
                   bundle_spec.PlacementGroupId().Hex(),
                   " is removed."));

The fix can be as simple as removing (work->GetState() == internal::WorkStatus::WAITING_FOR_WORKER) so that we cancel all lease requests requiring the PG not just those that are already WAITING_FOR_WORKER.

With that fix, our test can also be updated with another check to make sure the second actor is dead with the proper reason of

case rpc::RequestWorkerLeaseReply::SCHEDULING_CANCELLED_PLACEMENT_GROUP_REMOVED:
    error_msg = absl::StrCat(
        "Could not create the actor because its associated placement group was "
        "removed.\n",
        scheduling_failure_message);
    death_cause.mutable_actor_unschedulable_context()->set_error_message(error_msg);

WDYT?

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.

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.

@jjyao Sounds great, I'll make some changes later.

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.

@Catch-Bull Thanks and sorry for the back and forth on the fix.

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.

@Catch-Bull any updates on this?

@jjyao

jjyao commented May 21, 2025

Copy link
Copy Markdown
Contributor

Replaced by #53195

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

Labels

community-backlog community-contribution Contributed by the community core Issues that should be addressed in Ray Core @external-author-action-required Alternate tag for PRs where the author doesn't have labeling permission. go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Core] RayCheck failed: placement_group_resource_manager_->ReturnBundle(bundle_spec) Status not OK

5 participants