ray-data-gpu-idle-profiles / cpp_fix_v3.diff
rich7421's picture
Ray Data GPU idle profiles: four modes + before/after pinned-staging, plus repro code
fa05bf1 verified
Raw
History Blame Contribute Delete
38.8 kB
diff --git a/python/ray/_private/node.py b/python/ray/_private/node.py
index afd481353e..ac5853a858 100644
--- a/python/ray/_private/node.py
+++ b/python/ray/_private/node.py
@@ -1852,6 +1852,30 @@ class Node:
wait=wait,
)
+ def _raylet_graceful_shutdown_timeout(self, process):
+ # Written atomically by this raylet while it owns an Nsight worker/launcher.
+ # Use the raylet's effective config (which may come from another head node).
+ marker = os.path.join(
+ self.get_session_dir_path(), f"raylet-profiler-{process.pid}"
+ )
+ try:
+ with open(marker) as file:
+ return 5 + max(0, int(file.read())) / 1000
+ except (OSError, ValueError):
+ pass
+
+ # An explicit positive flush budget also opts into a longer graceful wait,
+ # e.g. when the marker cannot be published. Otherwise retain the 1s default.
+ flush_ms = max(
+ 0, int(self._resolve_ray_config("worker_profiler_flush_timeout_ms", 0))
+ )
+ if flush_ms == 0:
+ return 1
+ worker_ms = max(
+ 0, int(self._resolve_ray_config("kill_worker_timeout_milliseconds", 5000))
+ )
+ return 5 + (worker_ms + flush_ms) / 1000
+
def _kill_process_impl(
self, process_type, allow_graceful=False, check_alive=True, wait=False
):
@@ -1861,7 +1885,7 @@ class Node:
process_infos = self.all_processes[process_type]
if process_type != ray_constants.PROCESS_TYPE_REDIS_SERVER:
assert len(process_infos) == 1
- wait_timeout_seconds = 1
+ reap_timeout_seconds = 1
for process_info in process_infos:
process = process_info.process
# Handle the case where the process has already exited.
@@ -1898,12 +1922,27 @@ class Node:
time.sleep(0.1)
if allow_graceful:
+ graceful_start = time.monotonic()
+ graceful_timeout_seconds = (
+ self._raylet_graceful_shutdown_timeout(process)
+ if process_type == ray_constants.PROCESS_TYPE_RAYLET
+ else 1
+ )
process.terminate()
- # Allow the process one second to exit gracefully.
try:
- process.wait(timeout=wait_timeout_seconds)
+ process.wait(timeout=graceful_timeout_seconds)
except subprocess.TimeoutExpired:
- pass
+ # A worker can register between the initial marker read and
+ # SIGTERM. Recheck once, without restarting the graceful budget.
+ if process_type == ray_constants.PROCESS_TYPE_RAYLET:
+ remaining = self._raylet_graceful_shutdown_timeout(process) - (
+ time.monotonic() - graceful_start
+ )
+ if remaining > 0:
+ try:
+ process.wait(timeout=remaining)
+ except subprocess.TimeoutExpired:
+ pass
# If the process did not exit, force kill it.
if process.poll() is None:
@@ -1924,7 +1963,7 @@ class Node:
timeout = (
KILLED_PROCESS_REAP_TIMEOUT_SECONDS
if wait
- else wait_timeout_seconds
+ else reap_timeout_seconds
)
try:
process.wait(timeout=timeout)
diff --git a/src/ray/common/ray_config_def.h b/src/ray/common/ray_config_def.h
index ed640d1d4f..65b449fe4b 100644
--- a/src/ray/common/ray_config_def.h
+++ b/src/ray/common/ray_config_def.h
@@ -342,6 +342,11 @@ RAY_CONFIG(int64_t, raylet_client_connect_timeout_milliseconds, 1000)
/// the worker SIGKILL.
RAY_CONFIG(int64_t, kill_worker_timeout_milliseconds, 5000)
+/// Nsight launcher flush budget, starting when raylet observes its worker exit.
+/// Non-positive values disable only the post-worker-exit wait. Supported with
+/// process-group cleanup on Linux; force kill and registration failure are excluded.
+RAY_CONFIG(int64_t, worker_profiler_flush_timeout_ms, 10000)
+
/// Timeout for graceful actor shutdown (e.g. when actor goes out of scope).
/// If an actor does not gracefully shut down within this timeout, it will be force
/// killed. Set to -1 for infinite timeout to prevent the actor from being force killed
diff --git a/src/ray/raylet/BUILD.bazel b/src/ray/raylet/BUILD.bazel
index b0cd4c825b..0dc8928ab7 100644
--- a/src/ray/raylet/BUILD.bazel
+++ b/src/ray/raylet/BUILD.bazel
@@ -132,6 +132,7 @@ ray_cc_library(
"@com_google_absl//absl/random",
"@com_google_absl//absl/random:bit_gen_ref",
"@com_google_absl//absl/strings",
+ "@nlohmann_json",
],
)
@@ -357,6 +358,16 @@ ray_cc_library(
],
)
+ray_cc_library(
+ name = "shutdown",
+ hdrs = ["shutdown.h"],
+ visibility = [":__subpackages__"],
+ deps = [
+ "//src/ray/asio:instrumented_io_context",
+ "//src/ray/protobuf:gcs_cc_proto",
+ ],
+)
+
ray_cc_binary(
name = "raylet",
srcs = ["main.cc"],
@@ -370,6 +381,7 @@ ray_cc_binary(
":local_object_manager_interface",
":metrics",
":raylet_lib",
+ ":shutdown",
":worker_pool",
"//src/ray/asio:instrumented_io_context",
"//src/ray/asio:periodical_runner",
@@ -394,6 +406,7 @@ ray_cc_binary(
"//src/ray/util:cmd_line_utils",
"//src/ray/util:event",
"//src/ray/util:process",
+ "//src/ray/util:process_utils",
"//src/ray/util:raii",
"//src/ray/util:stream_redirection",
"//src/ray/util:stream_redirection_options",
diff --git a/src/ray/raylet/main.cc b/src/ray/raylet/main.cc
index e500e097f5..7d34eff183 100644
--- a/src/ray/raylet/main.cc
+++ b/src/ray/raylet/main.cc
@@ -48,6 +48,7 @@
#include "ray/raylet/local_object_manager_interface.h"
#include "ray/raylet/metrics.h"
#include "ray/raylet/node_manager.h"
+#include "ray/raylet/shutdown.h"
#include "ray/raylet/worker_pool.h"
#include "ray/raylet_ipc_client/client_connection.h"
#include "ray/raylet_rpc_client/raylet_client.h"
@@ -58,6 +59,7 @@
#include "ray/util/event.h"
#include "ray/util/network_util.h"
#include "ray/util/process.h"
+#include "ray/util/process_utils.h"
#include "ray/util/raii.h"
#include "ray/util/stream_redirection.h"
#include "ray/util/stream_redirection_options.h"
@@ -461,9 +463,10 @@ int main(int argc, char *argv[]) {
ray::NodeID raylet_node_id = ray::NodeID::FromHex(node_id);
std::atomic_bool shutting_down = false;
- // Shut down raylet gracefully, in a synchronous fashion.
- // This can be run by the signal handler or on the main io service.
- auto shutdown_raylet_gracefully =
+ // Agent monitors and signal handlers share this entry point. Post all teardown
+ // to the main executor, which must keep serving worker disconnect replies.
+ auto shutdown_raylet_gracefully = ray::raylet::MakeRayletShutdownCallback(
+ main_service,
[raylet_node_id,
&shutting_down,
&node_manager,
@@ -511,9 +514,15 @@ int main(int argc, char *argv[]) {
remove(raylet_socket_name.c_str());
};
- gcs_client->Nodes().UnregisterSelf(
- raylet_node_id, node_death_info, std::move(unregister_done_callback));
- };
+ node_manager->PrepareForShutdown(
+ [&gcs_client,
+ raylet_node_id,
+ node_death_info,
+ done = std::move(unregister_done_callback)]() mutable {
+ gcs_client->Nodes().UnregisterSelf(
+ raylet_node_id, node_death_info, std::move(done));
+ });
+ });
gcs_client->InternalKV().AsyncGetInternalConfig([&](::ray::Status status,
const std::optional<std::string>
@@ -753,7 +762,8 @@ int main(int argc, char *argv[]) {
node_manager_config.ray_debugger_external,
/*clock=*/clock,
worker_pool_metrics,
- std::move(add_process_to_workers_cgroup_hook));
+ std::move(add_process_to_workers_cgroup_hook),
+ session_dir + "/raylet-profiler-" + std::to_string(ray::GetPID()));
client_call_manager = std::make_unique<ray::rpc::ClientCallManager>(
main_service, /*record_stats=*/true, node_ip_address);
diff --git a/src/ray/raylet/node_manager.cc b/src/ray/raylet/node_manager.cc
index ff9e598c9c..4514162f4b 100644
--- a/src/ray/raylet/node_manager.cc
+++ b/src/ray/raylet/node_manager.cc
@@ -1630,7 +1630,9 @@ void NodeManager::DisconnectClient(const std::shared_ptr<ClientConnection> &clie
<< "using process groups for worker cleanup. "
<< "Subreaper is deprecated and will be removed in a future release.";
}
- if (pg_enabled) {
+ const bool profiler_cleanup =
+ worker_pool_.DeferProfilerCleanup(worker->WorkerId(), graceful);
+ if (pg_enabled && !profiler_cleanup) {
auto saved = worker->GetSavedProcessGroupId();
if (saved.has_value()) {
const auto wid = worker->WorkerId();
@@ -3042,7 +3044,12 @@ void NodeManager::HandleGetAgentPIDs(rpc::GetAgentPIDsRequest request,
send_reply_callback(Status::OK(), /* success */ nullptr, /* failure */ nullptr);
}
+void NodeManager::PrepareForShutdown(std::function<void()> done) {
+ worker_pool_.PrepareProfilerShutdown(std::move(done));
+}
+
void NodeManager::Stop() {
+ worker_pool_.DrainProfilerProcesses();
store_client_->Disconnect();
#if !defined(_WIN32)
// Best-effort process-group cleanup for any remaining workers before shutdown.
diff --git a/src/ray/raylet/node_manager.h b/src/ray/raylet/node_manager.h
index dc42ad231a..ca6722355e 100644
--- a/src/ray/raylet/node_manager.h
+++ b/src/ray/raylet/node_manager.h
@@ -251,6 +251,9 @@ class NodeManager : public rpc::NodeManagerServiceHandler,
/// or object ids can be freed up across the cluster.
void SetShouldGlobalGC();
+ /// Complete profiled worker shutdown while the executor serves disconnect replies.
+ void PrepareForShutdown(std::function<void()> done);
+
/// Stop this node manager.
void Stop();
diff --git a/src/ray/raylet/shutdown.h b/src/ray/raylet/shutdown.h
new file mode 100644
index 0000000000..953d80a294
--- /dev/null
+++ b/src/ray/raylet/shutdown.h
@@ -0,0 +1,37 @@
+// Copyright 2017 The Ray Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+
+#include <functional>
+#include <utility>
+
+#include "ray/asio/instrumented_io_context.h"
+#include "src/ray/protobuf/gcs.pb.h"
+
+namespace ray::raylet {
+
+/// Agent monitor threads may invoke shutdown. Copy the death info and always post
+/// the callback so teardown never runs inline on a monitor thread.
+inline std::function<void(const rpc::NodeDeathInfo &)> MakeRayletShutdownCallback(
+ instrumented_io_context &io_service,
+ std::function<void(const rpc::NodeDeathInfo &)> shutdown) {
+ return [&io_service, shutdown = std::move(shutdown)](
+ const rpc::NodeDeathInfo &death_info) {
+ io_service.post([shutdown, death_info] { shutdown(death_info); },
+ "Raylet.Shutdown");
+ };
+}
+
+} // namespace ray::raylet
diff --git a/src/ray/raylet/tests/BUILD.bazel b/src/ray/raylet/tests/BUILD.bazel
index 8640c518de..61b55b124b 100644
--- a/src/ray/raylet/tests/BUILD.bazel
+++ b/src/ray/raylet/tests/BUILD.bazel
@@ -39,6 +39,7 @@ ray_cc_test(
"//:ray_mock",
"//src/ray/asio:periodical_runner",
"//src/ray/core_worker_rpc_client:fake_core_worker_client",
+ "//src/ray/raylet:shutdown",
"//src/ray/raylet:worker",
"//src/ray/raylet:worker_pool",
"//src/ray/util:clock",
diff --git a/src/ray/raylet/tests/worker_pool_test.cc b/src/ray/raylet/tests/worker_pool_test.cc
index bb288cc657..c02eb025fb 100644
--- a/src/ray/raylet/tests/worker_pool_test.cc
+++ b/src/ray/raylet/tests/worker_pool_test.cc
@@ -18,11 +18,14 @@
#include <gtest/gtest.h>
#include <algorithm>
+#include <cerrno>
+#include <csignal>
#include <iostream>
#include <list>
#include <memory>
#include <random>
#include <string>
+#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <utility>
@@ -40,6 +43,7 @@
#include "ray/core_worker_rpc_client/fake_core_worker_client.h"
#include "ray/observability/fake_metric.h"
#include "ray/raylet/runtime_env_agent_client.h"
+#include "ray/raylet/shutdown.h"
#include "ray/raylet/worker.h"
#include "ray/util/clock.h"
#include "ray/util/fake_process.h"
@@ -49,6 +53,11 @@
#include "ray/util/raii.h"
#include "src/ray/protobuf/runtime_env_agent.pb.h"
+#if defined(__linux__)
+#include <sys/wait.h>
+#include <unistd.h>
+#endif
+
using json = nlohmann::json;
namespace ray::raylet {
@@ -2742,4 +2751,216 @@ TEST_F(WorkerPoolPortRangeTest, AssignsUniquePortsFromTheConfiguredRange) {
}
}
+#if defined(__linux__)
+class CountingProfilerProcess : public FakeProcess {
+ public:
+ using FakeProcess::FakeProcess;
+ bool IsAlive() const override {
+ ++probes;
+ return FakeProcess::IsAlive();
+ }
+ pid_t GetId() const override {
+ ++pid_reads;
+ return FakeProcess::GetId();
+ }
+ void Kill() override {
+ ++kills;
+ FakeProcess::Kill();
+ }
+ mutable int probes = 0;
+ mutable int pid_reads = 0;
+ int kills = 0;
+};
+
+class WorkerPoolProfilerTest : public WorkerPoolTest {
+ public:
+ void SetUp() override {
+ WorkerPoolTest::SetUp();
+ io_service_.stop();
+ thread_io_service_->join();
+ io_service_.restart();
+ RayConfig::instance().initialize(
+ R"({"process_group_cleanup_enabled":true,
+ "kill_worker_timeout_milliseconds":100,
+ "worker_profiler_flush_timeout_ms":100})");
+ }
+ void TearDown() override {
+ for (auto &[_, profiler] : worker_pool_->profiler_processes_) {
+ worker_pool_->TryFinishProfiler(profiler, true);
+ }
+ worker_pool_->DrainProfilerProcesses();
+ worker_pool_.reset();
+ io_service_.stop();
+ runtime_env_reference.clear();
+ if (child_pid_ > 0) {
+ kill(child_pid_, SIGKILL);
+ while (waitpid(child_pid_, nullptr, 0) < 0 && errno == EINTR) {
+ }
+ }
+ }
+
+ struct Tracked {
+ std::shared_ptr<WorkerInterface> worker;
+ CountingProfilerProcess *process;
+ std::shared_ptr<CountingProfilerProcess> launcher;
+ };
+
+ Tracked Track(bool alive = false, pid_t pid = -1) {
+ const pid_t pgid = Process::PID_MAX_LIMIT + 100 + next_pid_++;
+ auto process =
+ std::make_unique<CountingProfilerProcess>(pid > 0 ? pid : pgid + 1000);
+ auto *ptr = process.get();
+ ptr->SetAlive(alive);
+ auto worker = worker_pool_->CreateWorker(WorkerID::FromRandom(), std::move(process));
+ auto launcher = std::make_shared<CountingProfilerProcess>(pgid);
+ worker->SetSavedProcessGroupId(pgid);
+ auto &state = worker_pool_->states_by_lang_[Language::PYTHON];
+ state.registered_workers.insert(worker);
+ auto &record = state.worker_processes[worker->WorkerId()];
+ record.worker_type = rpc::WorkerType::WORKER;
+ record.is_pending_registration = false;
+ record.proc = launcher;
+ record.profiler_cleanup_owned = true;
+ worker_pool_->profiler_processes_.emplace(
+ worker->WorkerId(), WorkerPool::ProfilerProcess{launcher, worker, pgid});
+ return {worker, ptr, launcher};
+ }
+
+ void Poll() { worker_pool_->PollProfilerProcesses(); }
+ auto &Entry(const Tracked &t) {
+ return worker_pool_->profiler_processes_.at(t.worker->WorkerId());
+ }
+ bool Owns(const Tracked &t) {
+ return worker_pool_->profiler_processes_.contains(t.worker->WorkerId());
+ }
+ bool FinishAgain(const Tracked &t) {
+ return worker_pool_->TryFinishProfiler(Entry(t), true);
+ }
+
+ protected:
+ pid_t child_pid_ = -1;
+
+ private:
+ int next_pid_ = 0;
+};
+
+TEST_F(WorkerPoolProfilerTest, ExitIsIrreversibleAndShutdownPreservesDeadline) {
+ auto t = Track();
+ EXPECT_TRUE(worker_pool_->DeferProfilerCleanup(t.worker->WorkerId(), true));
+ Poll();
+ auto deadline = Entry(t).flush_deadline;
+ ASSERT_TRUE(deadline.has_value());
+ const int probes = t.process->probes;
+ const int reads = t.process->pid_reads;
+ t.process->SetAlive(true); // The old numeric W PID has been reused.
+ fake_clock_.AdvanceTime(absl::Milliseconds(90));
+ bool done = false;
+ worker_pool_->PrepareProfilerShutdown([&] { done = true; });
+ EXPECT_EQ(Entry(t).flush_deadline, deadline);
+ EXPECT_FALSE(done);
+ fake_clock_.AdvanceTime(absl::Milliseconds(10));
+ Poll();
+ EXPECT_TRUE(done);
+ EXPECT_FALSE(Owns(t));
+ EXPECT_EQ(t.process->probes, probes);
+ EXPECT_EQ(t.process->pid_reads, reads);
+ EXPECT_EQ(t.launcher->kills, 1);
+ worker_pool_->DrainProfilerProcesses();
+ EXPECT_EQ(t.launcher->kills, 1);
+}
+
+TEST_F(WorkerPoolProfilerTest, ConsumedGroupSurvivesLateDisconnect) {
+ auto t = Track();
+ EXPECT_TRUE(worker_pool_->DeferProfilerCleanup(t.worker->WorkerId(), true));
+ Poll();
+ EXPECT_TRUE(FinishAgain(t));
+ EXPECT_EQ(Entry(t).pgid, -1);
+ t.launcher->SetAlive(true); // Simulate reuse after releasing the group.
+ EXPECT_TRUE(FinishAgain(t));
+ Poll();
+ EXPECT_FALSE(Owns(t));
+ EXPECT_TRUE(t.worker->IsDead());
+ EXPECT_TRUE(worker_pool_->GetAllRegisteredWorkers(true, false).empty());
+ ASSERT_EQ(worker_pool_->GetRegisteredWorker(t.worker->Connection()), t.worker);
+ // DisconnectClient queries this before removing the still-registered worker.
+ // Both EOF and graceful disconnect must skip its ordinary group cleanup.
+ EXPECT_TRUE(worker_pool_->DeferProfilerCleanup(t.worker->WorkerId(), false));
+ EXPECT_TRUE(worker_pool_->DeferProfilerCleanup(t.worker->WorkerId(), true));
+ worker_pool_->DisconnectWorker(t.worker, rpc::WorkerExitType::SYSTEM_ERROR);
+ EXPECT_EQ(worker_pool_->GetRegisteredWorker(t.worker->Connection()), nullptr);
+ worker_pool_->DrainProfilerProcesses();
+ EXPECT_EQ(t.launcher->kills, 1);
+}
+
+TEST_F(WorkerPoolProfilerTest, AgentShutdownYieldsAndForceKillsEscapedWorker) {
+ int ready[2];
+ ASSERT_EQ(pipe(ready), 0);
+ child_pid_ = fork();
+ if (child_pid_ == 0) {
+ close(ready[0]);
+ if (setsid() < 0) {
+ _exit(1);
+ }
+ signal(SIGTERM, SIG_IGN);
+ alarm(10); // A missing force kill fails by SIGALRM instead of hanging the test.
+ const char ok = 1;
+ if (write(ready[1], &ok, 1) != 1) {
+ _exit(2);
+ }
+ close(ready[1]);
+ for (;;) {
+ pause();
+ }
+ }
+ close(ready[1]);
+ char ok = 0;
+ const auto bytes = child_pid_ > 0 ? read(ready[0], &ok, 1) : -1;
+ close(ready[0]);
+ ASSERT_GT(child_pid_, 0);
+ ASSERT_EQ(bytes, 1);
+ auto t = Track(true, child_pid_);
+ ASSERT_EQ(getpgid(child_pid_), child_pid_);
+ ASSERT_NE(getpgid(child_pid_), *t.worker->GetSavedProcessGroupId());
+
+ bool prepared = false, done = false, replied = false;
+ auto shutdown = MakeRayletShutdownCallback(
+ io_service_, [&](const rpc::NodeDeathInfo &info) {
+ EXPECT_TRUE(io_service_.get_executor().running_in_this_thread());
+ EXPECT_EQ(info.reason_message(), "agent failed");
+ prepared = true;
+ worker_pool_->PrepareProfilerShutdown([&] { done = true; });
+ });
+ std::thread agent([&] {
+ rpc::NodeDeathInfo info;
+ info.set_reason_message("agent failed");
+ shutdown(info);
+ info.set_reason_message("caller reused its message");
+ });
+ agent.join();
+ EXPECT_FALSE(prepared);
+ io_service_.post([&] { replied = true; }, "test.disconnect_reply");
+ io_service_.poll();
+ EXPECT_TRUE(prepared);
+ EXPECT_TRUE(replied);
+ EXPECT_FALSE(done);
+ EXPECT_EQ(kill(child_pid_, 0), 0);
+
+ // DestroyWorker disconnects first, then calls KillAsync, which MarkDead suppresses.
+ EXPECT_TRUE(worker_pool_->DeferProfilerCleanup(t.worker->WorkerId(), false));
+ t.worker->KillAsync(io_service_, true);
+ int status = 0;
+ pid_t reaped;
+ do {
+ reaped = waitpid(child_pid_, &status, 0);
+ } while (reaped < 0 && errno == EINTR);
+ ASSERT_EQ(reaped, child_pid_);
+ child_pid_ = -1;
+ ASSERT_TRUE(WIFSIGNALED(status));
+ EXPECT_EQ(WTERMSIG(status), SIGKILL);
+ Poll();
+ EXPECT_TRUE(done);
+ EXPECT_EQ(t.launcher->kills, 1);
+}
+#endif
+
} // namespace ray::raylet
diff --git a/src/ray/raylet/worker_pool.cc b/src/ray/raylet/worker_pool.cc
index 93323ba7b2..679dd5defa 100644
--- a/src/ray/raylet/worker_pool.cc
+++ b/src/ray/raylet/worker_pool.cc
@@ -16,12 +16,17 @@
#include <algorithm>
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <cerrno>
+#include <chrono>
+#include <csignal>
+#include <cstdio>
#include <deque>
#include <fstream>
#include <iostream>
#include <memory>
#include <optional>
#include <string>
+#include <thread>
#include <tuple>
#include <unordered_set>
#include <utility>
@@ -30,6 +35,7 @@
#include "absl/random/random.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_split.h"
+#include "nlohmann/json.hpp"
#include "ray/common/constants.h"
#include "ray/common/lease/lease_spec.h"
#include "ray/common/protobuf_utils.h"
@@ -139,8 +145,10 @@ WorkerPool::WorkerPool(instrumented_io_context &io_service,
int ray_debugger_external,
ClockInterface &clock,
WorkerPoolMetrics &worker_pool_metrics,
- AddProcessToCgroupHook add_to_cgroup_hook)
+ AddProcessToCgroupHook add_to_cgroup_hook,
+ std::string profiler_shutdown_marker_path)
: clock_(clock),
+ profiler_shutdown_marker_path_(std::move(profiler_shutdown_marker_path)),
io_service_(&io_service),
node_id_(node_id),
node_address_(std::move(node_address)),
@@ -195,13 +203,20 @@ WorkerPool::WorkerPool(instrumented_io_context &io_service,
RAY_LOG(INFO) << "Initialized the worker port pool with " << ports.size()
<< " shuffled ports.";
}
+#if defined(__linux__)
+ UpdateProfilerShutdownMarker();
+#endif
}
WorkerPool::~WorkerPool() {
- absl::flat_hash_map<pid_t, std::unique_ptr<ProcessInterface>> procs_to_kill;
+ DrainProfilerProcesses();
+ absl::flat_hash_map<pid_t, std::shared_ptr<ProcessInterface>> procs_to_kill;
for (auto &entry : states_by_lang_) {
// Kill all the worker processes.
for (auto &worker_process : entry.second.worker_processes) {
+ if (worker_process.second.profiler_cleanup_owned) {
+ continue;
+ }
auto pid = worker_process.second.proc->GetId();
procs_to_kill.try_emplace(pid, std::move(worker_process.second.proc));
}
@@ -212,6 +227,223 @@ WorkerPool::~WorkerPool() {
}
}
+#if defined(__linux__)
+bool WorkerPool::TryFinishProfiler(ProfilerProcess &profiler, bool force) {
+ if (profiler.state == ProfilerState::finished) {
+ return true;
+ }
+ const auto now = clock_.SteadyNow();
+ if (!force) {
+ if (profiler.state == ProfilerState::waiting_for_worker_exit) {
+ if (profiler.worker->GetProcess().IsAlive()) {
+ return false;
+ }
+ profiler.state = ProfilerState::flushing;
+ profiler.flush_deadline =
+ now + std::chrono::milliseconds(std::max<int64_t>(
+ 0, RayConfig::instance().worker_profiler_flush_timeout_ms()));
+ }
+ // Once flushing, never probe or signal the old worker PID again.
+ if (now < *profiler.flush_deadline && profiler.launcher->IsAlive()) {
+ return false;
+ }
+ }
+ // W may have escaped the saved process group (e.g. via setsid). Terminate it
+ // directly before MarkDead suppresses DestroyWorker's subsequent KillAsync.
+ // Never touch W's old PID once its exit has been observed.
+ if (profiler.state == ProfilerState::waiting_for_worker_exit &&
+ !profiler.worker_kill_sent) {
+ profiler.worker_kill_sent = true;
+ kill(profiler.worker->GetProcess().GetId(), SIGKILL);
+ }
+ // Consume ownership before signaling the launcher/group. Stop filters dead
+ // workers; the process record retains ownership until DisconnectWorker.
+ profiler.state = ProfilerState::finished;
+ profiler.worker->MarkDead();
+ const auto pgid = std::exchange(profiler.pgid, -1);
+ if (profiler.launcher->IsAlive()) {
+ profiler.launcher->Kill();
+ }
+ RAY_LOG(INFO).WithField(profiler.worker->WorkerId())
+ << "Profiler cleanup: sending SIGKILL to pgid=" << pgid;
+ auto error = KillProcessGroup(pgid, SIGKILL);
+ if (error && *error && error->value() != ESRCH) {
+ RAY_LOG(WARNING) << "Profiler group cleanup failed: " << error->message();
+ }
+ return true;
+}
+
+void WorkerPool::UpdateProfilerShutdownMarker() {
+ if (profiler_shutdown_marker_path_.empty()) {
+ return;
+ }
+ if (profiler_processes_.empty()) {
+ std::remove(profiler_shutdown_marker_path_.c_str());
+ return;
+ }
+ // Publish the effective C++ budget, including on non-head nodes. Python only
+ // extends its graceful wait while this raylet owns a profiled worker/launcher.
+ const auto timeout_ms =
+ std::max<int64_t>(0, RayConfig::instance().kill_worker_timeout_milliseconds()) +
+ std::max<int64_t>(0, RayConfig::instance().worker_profiler_flush_timeout_ms());
+ const auto temporary = profiler_shutdown_marker_path_ + ".tmp";
+ std::ofstream marker(temporary);
+ marker << timeout_ms;
+ marker.close();
+ if (!marker || std::rename(temporary.c_str(), profiler_shutdown_marker_path_.c_str())) {
+ RAY_LOG(WARNING) << "Could not publish profiler shutdown budget";
+ std::remove(temporary.c_str());
+ }
+}
+
+void WorkerPool::ScheduleProfilerPoll() {
+ if (profiler_timer_pending_) {
+ return;
+ }
+ if (!profiler_timer_) {
+ profiler_timer_ = std::make_unique<boost::asio::steady_timer>(*io_service_);
+ }
+ profiler_timer_pending_ = true;
+ profiler_timer_->expires_after(std::chrono::milliseconds(10));
+ profiler_timer_->async_wait(
+ [this, lifetime = std::weak_ptr<int>(profiler_lifetime_)](
+ const boost::system::error_code &ec) {
+ if (ec || lifetime.expired()) {
+ return;
+ }
+ profiler_timer_pending_ = false;
+ PollProfilerProcesses();
+ });
+}
+
+void WorkerPool::PollProfilerProcesses() {
+ bool pending = false;
+ const auto now = clock_.SteadyNow();
+ for (auto it = profiler_processes_.begin(); it != profiler_processes_.end();) {
+ auto &profiler = it->second;
+ if (!profiler.cleanup_requested) {
+ ++it;
+ continue;
+ }
+ const bool force =
+ profiler_shutdown_deadline_ && now >= *profiler_shutdown_deadline_;
+ if (TryFinishProfiler(profiler, force)) {
+ profiler_processes_.erase(it++);
+ if (profiler_processes_.empty()) {
+ UpdateProfilerShutdownMarker();
+ }
+ continue;
+ }
+ if (profiler.state == ProfilerState::waiting_for_worker_exit &&
+ profiler_worker_exit_deadline_ && now >= *profiler_worker_exit_deadline_ &&
+ !profiler.worker_kill_sent) {
+ profiler.worker_kill_sent = true;
+ kill(profiler.worker->GetProcess().GetId(), SIGKILL);
+ }
+ pending = true;
+ ++it;
+ }
+ if (pending) {
+ ScheduleProfilerPoll();
+ } else if (profiler_shutdown_done_) {
+ auto done = std::move(profiler_shutdown_done_);
+ done(); // May destroy the pool; do not access members afterwards.
+ }
+}
+#endif
+
+bool WorkerPool::DeferProfilerCleanup(const WorkerID &worker_id, bool graceful) {
+#if defined(__linux__)
+ auto it = profiler_processes_.find(worker_id);
+ if (it != profiler_processes_.end()) {
+ if (!graceful) {
+ TryFinishProfiler(it->second, true);
+ profiler_processes_.erase(it);
+ if (profiler_processes_.empty()) {
+ UpdateProfilerShutdownMarker();
+ }
+ return true;
+ }
+ it->second.cleanup_requested = true;
+ // Do not finish inline: DisconnectClient must send its reply first.
+ ScheduleProfilerPoll();
+ return true;
+ }
+ // Terminal cleanup can precede a late EOF while the worker is still registered.
+ // Its record outlives the registry entry, so disconnect must not reacquire PGID.
+ for (const auto &[_, state] : states_by_lang_) {
+ auto process = state.worker_processes.find(worker_id);
+ if (process != state.worker_processes.end() &&
+ process->second.profiler_cleanup_owned) {
+ return true;
+ }
+ }
+#endif
+ return false;
+}
+
+void WorkerPool::PrepareProfilerShutdown(std::function<void()> done) {
+ RAY_CHECK(!profiler_shutdown_started_);
+ profiler_shutdown_started_ = true;
+#if defined(__linux__)
+ const auto now = clock_.SteadyNow();
+ profiler_worker_exit_deadline_ =
+ now + std::chrono::milliseconds(std::max<int64_t>(
+ 0, RayConfig::instance().kill_worker_timeout_milliseconds()));
+ profiler_shutdown_deadline_ =
+ *profiler_worker_exit_deadline_ +
+ std::chrono::milliseconds(std::max<int64_t>(
+ 0, RayConfig::instance().worker_profiler_flush_timeout_ms()));
+ profiler_shutdown_done_ = std::move(done);
+ for (auto &[_, profiler] : profiler_processes_) {
+ profiler.cleanup_requested = true;
+ // Observe exit before signaling, preserving any existing flush deadline.
+ if (!TryFinishProfiler(profiler, false) &&
+ profiler.state == ProfilerState::waiting_for_worker_exit) {
+ kill(profiler.worker->GetProcess().GetId(), SIGTERM);
+ }
+ }
+ PollProfilerProcesses();
+#else
+ done();
+#endif
+}
+
+void WorkerPool::DrainProfilerProcesses() {
+#if defined(__linux__)
+ profiler_lifetime_.reset();
+ if (profiler_timer_) {
+ boost::system::error_code ignored;
+ profiler_timer_->cancel(ignored);
+ }
+ profiler_shutdown_done_ = nullptr;
+ // This is a fallback for Stop/destruction without PrepareProfilerShutdown.
+ // Never wait for a live W here: it may need a disconnect reply on this executor.
+ // Only launchers whose W has exited may consume their remaining flush budget.
+ while (!profiler_processes_.empty()) {
+ for (auto it = profiler_processes_.begin(); it != profiler_processes_.end();) {
+ auto &profiler = it->second;
+ bool finished = TryFinishProfiler(profiler, false);
+ if (!finished &&
+ (profiler.state == ProfilerState::waiting_for_worker_exit ||
+ (profiler_shutdown_deadline_ &&
+ clock_.SteadyNow() >= *profiler_shutdown_deadline_))) {
+ finished = TryFinishProfiler(profiler, true);
+ }
+ if (finished) {
+ profiler_processes_.erase(it++);
+ } else {
+ ++it;
+ }
+ }
+ if (!profiler_processes_.empty()) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ }
+ }
+ UpdateProfilerShutdownMarker();
+#endif
+}
+
void WorkerPool::Start() {
if (RayConfig::instance().kill_idle_workers_interval_ms() > 0) {
periodical_runner_->RunFnPeriodically(
@@ -864,6 +1096,11 @@ Status WorkerPool::RegisterWorker(const std::shared_ptr<WorkerInterface> &worker
pid_t pid,
std::function<void(Status, int)> send_reply_callback) {
RAY_CHECK(worker);
+ if (profiler_shutdown_started_) {
+ const auto status = Status::Invalid("Raylet is shutting down");
+ send_reply_callback(status, /*port=*/0);
+ return status;
+ }
auto &state = GetStateForLanguage(worker->GetLanguage());
const WorkerID &worker_id = worker->WorkerId();
auto it = state.worker_processes.find(worker_id);
@@ -911,6 +1148,28 @@ Status WorkerPool::RegisterWorker(const std::shared_ptr<WorkerInterface> &worker
<< ", worker_type: " << rpc::WorkerType_Name(worker->GetWorkerType());
worker->SetAssignedPort(port);
+#if defined(__linux__)
+ // Nsight's launcher exports after the registered Python process exits.
+ // P != W alone is insufficient (e.g. py_executable wrappers or rocprof-sys).
+ if (RayConfig::instance().process_group_cleanup_enabled() &&
+ worker->GetLanguage() == Language::PYTHON && it->second.proc->GetId() != pid) {
+ const auto env = nlohmann::json::parse(
+ it->second.runtime_env_info.serialized_runtime_env(), nullptr, false);
+ const auto saved = worker->GetSavedProcessGroupId();
+ if (env.is_object() && env.contains("_nsight") &&
+ (env["_nsight"] == "default" ||
+ (env["_nsight"].is_object() && !env["_nsight"].empty())) &&
+ saved && *saved > 1 && *saved != getpgrp()) {
+ const bool first = profiler_processes_.empty();
+ profiler_processes_.emplace(
+ worker_id, ProfilerProcess{it->second.proc, worker, *saved});
+ it->second.profiler_cleanup_owned = true;
+ if (first) {
+ UpdateProfilerShutdownMarker();
+ }
+ }
+ }
+#endif
state.registered_workers.insert(worker);
// Send the reply immediately for worker registrations.
diff --git a/src/ray/raylet/worker_pool.h b/src/ray/raylet/worker_pool.h
index b6a0a3447d..3439f3b4df 100644
--- a/src/ray/raylet/worker_pool.h
+++ b/src/ray/raylet/worker_pool.h
@@ -18,6 +18,7 @@
#include <algorithm>
#include <boost/asio/io_service.hpp>
+#include <boost/asio/steady_timer.hpp>
#include <boost/functional/hash.hpp>
#include <deque>
#include <list>
@@ -197,6 +198,13 @@ class IOWorkerPoolInterface {
/// Used for new scheduler unit tests.
class WorkerPoolInterface : public IOWorkerPoolInterface {
public:
+ /// Own group cleanup for a registered Nsight worker; defer only graceful exits.
+ virtual bool DeferProfilerCleanup(const WorkerID &, bool graceful) { return false; }
+ /// Run before Stop, with the main event loop still serving disconnect replies.
+ virtual void PrepareProfilerShutdown(std::function<void()> done) { done(); }
+ /// Drain exited workers' launchers; force-finish live workers without an IPC wait.
+ virtual void DrainProfilerProcesses() {}
+
/// Pop an idle worker from the pool. The caller is responsible for pushing
/// the worker back onto the pool once the worker has completed its work.
///
@@ -322,6 +330,10 @@ inline std::ostream &operator<<(std::ostream &os,
/// is a container for a unit of work.
class WorkerPool : public WorkerPoolInterface {
public:
+ bool DeferProfilerCleanup(const WorkerID &worker_id, bool graceful) override;
+ void PrepareProfilerShutdown(std::function<void()> done) override;
+ void DrainProfilerProcesses() override;
+
/// Create a pool and asynchronously start at least the specified number of workers per
/// language.
/// Once each worker process has registered with an external server, the
@@ -371,7 +383,8 @@ class WorkerPool : public WorkerPoolInterface {
int ray_debugger_external,
ClockInterface &clock,
WorkerPoolMetrics &worker_pool_metrics,
- AddProcessToCgroupHook add_to_cgroup_hook = [](const std::string &) {});
+ AddProcessToCgroupHook add_to_cgroup_hook = [](const std::string &) {},
+ std::string profiler_shutdown_marker_path = "");
/// Destructor responsible for freeing a set of workers owned by this class.
~WorkerPool() override;
@@ -682,8 +695,8 @@ class WorkerPool : public WorkerPoolInterface {
bool is_pending_registration = true;
/// The type of the worker.
rpc::WorkerType worker_type;
- /// The worker process instance.
- std::unique_ptr<ProcessInterface> proc;
+ /// Retained by profiler_processes_ until post-worker-exit export completes.
+ std::shared_ptr<ProcessInterface> proc;
/// The worker process start time (monotonic, for measuring startup latency).
SteadyTimePoint start_time;
/// The runtime env Info.
@@ -692,6 +705,8 @@ class WorkerPool : public WorkerPoolInterface {
std::vector<std::string> dynamic_options;
/// The duration to keep the newly created worker alive before it's assigned a lease.
std::optional<absl::Duration> worker_startup_keep_alive_duration;
+ /// Profiler cleanup owns this group, even after completion, until disconnect.
+ bool profiler_cleanup_owned = false;
};
/// An internal data structure that maintains the pool state per language.
@@ -746,6 +761,35 @@ class WorkerPool : public WorkerPoolInterface {
std::list<IdleWorkerEntry> idle_of_all_languages_;
private:
+#if defined(__linux__)
+ enum class ProfilerState { waiting_for_worker_exit, flushing, finished };
+ struct ProfilerProcess {
+ std::shared_ptr<ProcessInterface> launcher;
+ std::shared_ptr<WorkerInterface> worker;
+ pid_t pgid;
+ ProfilerState state = ProfilerState::waiting_for_worker_exit;
+ bool cleanup_requested = false;
+ bool worker_kill_sent = false;
+ std::optional<SteadyTimePoint> flush_deadline = std::nullopt;
+ };
+ // All access, including destruction, is serialized with the main executor.
+ // Retains launcher ownership after DisconnectWorker removes the process record.
+ absl::flat_hash_map<WorkerID, ProfilerProcess> profiler_processes_;
+ std::unique_ptr<boost::asio::steady_timer> profiler_timer_;
+ // Cancellation alone does not invalidate an already queued successful callback.
+ std::shared_ptr<int> profiler_lifetime_ = std::make_shared<int>(0);
+ bool profiler_timer_pending_ = false;
+ std::optional<SteadyTimePoint> profiler_worker_exit_deadline_;
+ std::optional<SteadyTimePoint> profiler_shutdown_deadline_;
+ std::function<void()> profiler_shutdown_done_;
+ bool TryFinishProfiler(ProfilerProcess &profiler, bool force);
+ void PollProfilerProcesses();
+ void ScheduleProfilerPoll();
+ void UpdateProfilerShutdownMarker();
+#endif
+ bool profiler_shutdown_started_ = false;
+ const std::string profiler_shutdown_marker_path_;
+
/// A helper function that returns the reference of the pool state
/// for a given language.
State &GetStateForLanguage(const Language &language);
@@ -975,6 +1019,7 @@ class WorkerPool : public WorkerPoolInterface {
static inline const ProcessInterface &kNullProcess = Process();
friend class WorkerPoolTest;
+ friend class WorkerPoolProfilerTest;
friend class WorkerPoolDriverRegisteredTest;
};