diff --git a/src/ray/core_worker/actor_manager.cc b/src/ray/core_worker/actor_manager.cc index 4346d1eff96d..f3d354dbc439 100644 --- a/src/ray/core_worker/actor_manager.cc +++ b/src/ray/core_worker/actor_manager.cc @@ -205,7 +205,19 @@ bool ActorManager::AddActorHandle(std::unique_ptr actor_handle, } void ActorManager::OnActorKilled(const ActorID &actor_id) { - MarkActorKilledOrOutOfScope(GetActorHandle(actor_id)); + auto actor_handle = GetActorHandleIfExists(actor_id); + if (actor_handle == nullptr) { + // The actor handle may not exist if: + // 1. The actor was created in a previous Ray session and the user is trying + // to kill it after ray.shutdown() and ray.init(). + // 2. The actor handle was already removed for some other reason. + // In these cases, we simply log a warning and return instead of crashing. + RAY_LOG(WARNING) << "Cannot find actor handle for actor_id " << actor_id + << ". The actor may have been created in a different Ray session " + << "or already been cleaned up."; + return; + } + MarkActorKilledOrOutOfScope(actor_handle); } void ActorManager::WaitForActorRefDeleted( diff --git a/src/ray/core_worker/tests/actor_manager_test.cc b/src/ray/core_worker/tests/actor_manager_test.cc index 79e46745454b..194c29353e7f 100644 --- a/src/ray/core_worker/tests/actor_manager_test.cc +++ b/src/ray/core_worker/tests/actor_manager_test.cc @@ -393,6 +393,23 @@ TEST_F(ActorManagerTest, TestNamedActorIsKilledBeforeSubscribeFinished) { ASSERT_TRUE(actor_manager_->GetCachedNamedActorID(cached_actor_name).IsNil()); } +// Test that OnActorKilled does not crash when the actor handle does not exist. +// This can happen when the actor was created in a previous Ray session. +// Fixes https://github.com/ray-project/ray/issues/59340 +TEST_F(ActorManagerTest, TestOnActorKilledWithNonExistentHandle) { + // Create a random actor ID that does not have a registered handle. + ActorID non_existent_actor_id = ActorID::Of(JobID::FromInt(1), TaskID::Nil(), 1); + + // Verify that the actor handle does not exist. + ASSERT_FALSE(actor_manager_->CheckActorHandleExists(non_existent_actor_id)); + + // Call OnActorKilled with a non-existent actor ID. + // This should NOT crash - it should log a warning and return gracefully. + actor_manager_->OnActorKilled(non_existent_actor_id); + + // The test passes if we reach here without crashing. +} + } // namespace core } // namespace ray