Skip to content

[core][gcs][Actice-Passive] Phase 2.2 Add Active-Passive leader-election RPC gating - #65711

Merged
rueian merged 10 commits into
ray-project:masterfrom
YoyinZyc:passive_gcs_gating
Sep 15, 2026
Merged

rueian merged 10 commits into
ray-project:masterfrom
YoyinZyc:passive_gcs_gating

Conversation

@YoyinZyc

@YoyinZyc YoyinZyc commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

This is the C++ RPC-gating layer for the Active-Passive GCS feature (split from the larger #64422, following the interface PR #65132). It adds the server-side mechanism that, when a GCS is not the active leader, rejects mutating RPCs with Status::GcsPassive() while forwarding bootstrap/read RPCs. Everything is gated behind LEADER_ELECT, which defaults to off, so a normal single-GCS cluster behaves exactly as before.

This PR intentionally contains only the gating mechanism. The deferred-loading / promotion lifecycle (which flips a GCS from passive to active, updates the is_leader and the clears the passive_local_node_) and the end-to-end passive-head startup are in a follow-up PR. Since the gcs hasn't connected with the leader election model, setting LEADER_ELECT will not have gcs leader election behavior.

AI assistance was used to prepare this change.

Issue

#63643

High-level changes

Area Change
Leader-gated proxy handlers New gcs_leader_gated_handlers.h: a per-service proxy (LeaderGated*Handler) that wraps each real GCS service handler. GCS_GATED_RPC / GCS_ALLOWED_RPC macros make each RPC's gated-or-allowed status a single, auditable line; adding a new RPC to a service is a compile-time-enforced one-liner.
GcsNodeManager leadership + passive cache Injects an is_leader_fn (defaults to []{return true;}), reports it in HandleCheckAlive via reply->set_is_leader(...), and adds an in-memory passive_local_node_ cache (CachePassiveLocalNode) so the local head node is visible while passive and flushed through the normal RegisterNode path on promotion.
Centralized service registration All 14 rpc_server_.RegisterService(...) calls are moved out of the individual InitXxx() methods into one GcsServer::RegisterRpcServices(), called from DoStart after all managers are constructed. Gated services go through MaybeGate; RaySyncer is registered in an explicit "intentionally NOT gated" section with a documented rationale.

Test plan

Unit (C++) — new

  • gcs_leader_gated_handlers_test.cc
  • gcs_node_manager_test.cc
  • gcs_client_test.cc

Integration / backward-compat (C++) — existing

  • gcs_server_rpc_test

Real-cluster smoke (default config, LEADER_ELECT off)

  • ensure backward compatibility

@YoyinZyc
YoyinZyc requested a review from a team as a code owner August 24, 2026 23:59

@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 introduces active-passive leader election gating for the GCS server. It centralizes service registration and wraps GCS handlers in leader-gated proxies that reject mutating RPCs with a passive status when the GCS is passive, while allowing bootstrap and read-only RPCs. Additionally, GcsNodeManager is updated to cache the local head node in-memory while passive. The review feedback highlights a potential race condition in CachePassiveLocalNode that could trigger a crash via RAY_CHECK if promotion occurs during registration, as well as potential duplicate node entries in GetAllNodeInfo and GetAllNodeAddressAndLiveness if the passive local node is already present in the alive or dead node lists.

Comment thread src/ray/gcs/gcs_node_manager.h Resolved
Comment thread src/ray/gcs/gcs_node_manager.cc Resolved
Comment thread src/ray/gcs/gcs_node_manager.cc Resolved
Comment thread src/ray/gcs/gcs_leader_gated_handlers.h Resolved
@YoyinZyc
YoyinZyc force-pushed the passive_gcs_gating branch from f924b1b to a1303fd Compare August 25, 2026 00:31
@YoyinZyc

Copy link
Copy Markdown
Contributor Author

@rueian Please take a look. Thanks!!

Comment thread src/ray/gcs/gcs_node_manager.cc Resolved
@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Aug 25, 2026
@rueian rueian added the go add ONLY when ready to merge, run all tests label Aug 28, 2026
Comment thread src/ray/gcs/gcs_server.cc Outdated
Comment on lines +480 to +485
// Intentionally NOT leader-gated: RaySyncer is an in-memory resource-view
// stream (not a request/response handler).
// It has no shared-storage writes or leader-only side
// effects, so it is exempt.
rpc_server_.RegisterService(std::make_unique<syncer::RaySyncerService>(
*ray_syncer_, ray::rpc::AuthenticationTokenLoader::instance().GetToken()));

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 we try to gate RaySyncerService as well? I think making exceptions here is not good for our long term maintenance, we could then make more exceptions later on and accidentally forget to gate some endpoints.

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.

I think the RaySyncerService is bit special. It is a streaming service to sync the resource view among gcs and worker nodes. It is not like other request/reply based service which can follow the above pattern to gate.

The cluster should have two syncing group, 1. active head and worker node raylets 2. passive head and its own raylet. They should not cause any noise to each other. (The sync only happens among gcs and its registered workers)

updated the 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.

Honestly, having one streaming method in the service doesn't sound like a valid reason for not gating it. We may also add other streaming methods to other existing services as well.

@YoyinZyc YoyinZyc Sep 2, 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.

It is not just because it is streaming method.

  1. If it is easy to follow the centralized pattern, like other one-off handler style method. If yes, it is no harm to just add some lines for alignment; If not, that means we will leave more footprint which could potentially touch the given service code. Like for the raysyner, apparently it cannot fit into the current gating frame. It only has one StartSync method. After a raylet registers with GCS and finishes subscribing, it opens one stream to GCS. If we really want to gate it, we have to touch the raylet registration, meaning more footprint and more potential bug. Let me know if you have any better way to gate a streaming service in general.
  2. If we need to gate the service. The goal of gating is to prevent the passive from reaching to the redis. If the service does not do any write, it should be fine. In the meantime, we will add another layer of protection on redis end to prevent potential server-initiated writing which cannot be gated by the rpc gating anyway.
  3. If the promotion becomes hard to recover. Gating the normal service will not cause any trouble since they are one-off request. But gating the streaming service means we have to recover or re-initiate the streaming after promotion.

For the RaySyner:

  1. hard to gate as it is streaming service 2. not necessary to gate as it only shares in-memory resource-view 3. hard to recover after promotion

In this way, the easiest approach is to just keep it as it is.

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.

Or we could just skip registering the raysync service and defer it to promotion. However, I don't think it is a general approach either since some services must be register before promotion, so it is still an exception. And the promotion logic is not in this pr yet, for backward compatibility, we cannot do it yet.

@rueian rueian Sep 3, 2026 •

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.

Like for the raysyner, apparently it cannot fit into the current gating frame. It only has one StartSync method.

We still need a way to fit streaming methods into the gating frame, as we may introduce more streaming methods in the future. The new streaming method could be added to a new service or to an existing service. We shouldn't be blocked from doing that because the gating frame doesn't support streaming. We'd better support gating streaming methods now.

The goal of gating is to prevent the passive from reaching to the redis

Really? I thought it was for preventing workers or others from being accidentally confused by the standby and also protecting the standby from being polluted by others. If the goal is just to prevent the standby from reaching Redis, shouldn't we just implement the gating on the Redis client and keep these gRPC services intact?

not necessary to gate as it only shares in-memory resource-view

It is hard to tell if a method needs to be gated or not based on its current implementation. The implementation can be changed in the future and then have side effects. I think we'd best gate all of them until we identify that they shouldn't be gated, like those with GCS_ALLOWED_RPC.

  1. hard to recover after promotion

Why is it hard?

Or we could just skip registering the raysync service and defer it to promotion. However, I don't think it is a general approach either since some services must be register before promotion, so it is still an exception.

Agree, but deferring could actually be a good idea if we were able to defer ALL existing services and introduce a new specialized placeholder service to serve those GCS_ALLOWED_RPC methods before promotion.

Like for the raysyner, apparently it cannot fit into the current gating frame.

Is it really hard to make it fit into the gating frame? I am thinking something like this

diff --git a/src/ray/gcs/gcs_leader_gated_handlers.h b/src/ray/gcs/gcs_leader_gated_handlers.h
index 1d99512384..eb6442a293 100644
--- a/src/ray/gcs/gcs_leader_gated_handlers.h
+++ b/src/ray/gcs/gcs_leader_gated_handlers.h
@@ -20,6 +20,7 @@
 
 #include "ray/common/status.h"
 #include "ray/gcs/grpc_service_interfaces.h"
+#include "ray/ray_syncer/ray_syncer.h"
 
 namespace ray {
 namespace gcs {
@@ -94,6 +95,26 @@ namespace gcs {
         std::move(request), reply, std::move(send_reply_callback), grpc_peer); \
   }
 
+inline grpc::Status GcsPassiveGrpcStatus() {
+  return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
+                      Status::GcsPassive().message());
+}
+
+template <typename ReactorT>
+class RejectedStreamReactor : public ReactorT {
+ public:
+  explicit RejectedStreamReactor(grpc::Status status) { this->Finish(std::move(status)); }
+  void OnDone() override { delete this; }
+};
+
+#define GCS_GATED_BIDI_RPC(Method, Reactor)                              \
+  Reactor *Method(grpc::CallbackServerContext *context) override {       \
+    if (!is_leader_fn_()) {                                              \
+      return new RejectedStreamReactor<Reactor>(GcsPassiveGrpcStatus()); \
+    }                                                                    \
+    return handler_.Method(context);                                     \
+  }
+
 class LeaderGatedNodeInfoHandler : public rpc::NodeInfoGcsServiceHandler {
  public:
   using HandlerType = rpc::NodeInfoGcsServiceHandler;
@@ -490,12 +511,27 @@ class LeaderGatedRayEventExportHandler
   const std::function<bool()> is_leader_fn_;
 };
 
+class LeaderGatedRaySyncerHandler : public syncer::RaySyncerStreamHandler {
+ public:
+  using HandlerType = syncer::RaySyncerStreamHandler;
+  LeaderGatedRaySyncerHandler(syncer::RaySyncerStreamHandler &handler,
+                              std::function<bool()> is_leader_fn)
+      : handler_(handler), is_leader_fn_(std::move(is_leader_fn)) {}
+
+  GCS_GATED_BIDI_RPC(StartSync, syncer::SyncStreamReactor)
+
+ private:
+  syncer::RaySyncerStreamHandler &handler_;
+  const std::function<bool()> is_leader_fn_;
+};
+
 #undef GCS_PROXY_SEND_REPLY
 #undef GCS_GATED_RPC
 #undef GCS_GATED_RPC_PEER
 #undef GCS_ALLOWED_RPC
 #undef GCS_GATED_RPC_CB
 #undef GCS_GATED_RPC_CB_PEER
+#undef GCS_GATED_BIDI_RPC
 
 }  // namespace gcs
 }  // namespace ray
diff --git a/src/ray/gcs/gcs_server.cc b/src/ray/gcs/gcs_server.cc
index 1bf5566fad..204735aaaf 100644
--- a/src/ray/gcs/gcs_server.cc
+++ b/src/ray/gcs/gcs_server.cc
@@ -477,11 +477,10 @@ void GcsServer::RegisterRpcServices() {
         max_rpcs));
   }
 
-  // RaySyncer is an in-memory resource-view stream (not a request/response handler).
-  // It cannot follow the above pattern to be leader gated.
-  // It has no shared-storage writes or leader-only side effects, so it is exempt.
-  rpc_server_.RegisterService(std::make_unique<syncer::RaySyncerService>(
-      *ray_syncer_, ray::rpc::AuthenticationTokenLoader::instance().GetToken()));
+  ray_syncer_service_ = std::make_unique<syncer::RaySyncerService>(
+      *ray_syncer_, ray::rpc::AuthenticationTokenLoader::instance().GetToken());
+  rpc_server_.RegisterService(std::make_unique<syncer::RaySyncerGrpcService>(
+      MaybeGate(gated_ray_syncer_handler_, *ray_syncer_service_)));
 }
 
 void GcsServer::Stop() {
diff --git a/src/ray/gcs/gcs_server.h b/src/ray/gcs/gcs_server.h
index 5627fbd36f..97cdbb499d 100644
--- a/src/ray/gcs/gcs_server.h
+++ b/src/ray/gcs/gcs_server.h
@@ -336,6 +336,7 @@ class GcsServer {
   std::unique_ptr<LeaderGatedObservabilityPubSubHandler>
       gated_observability_pubsub_handler_;
   std::unique_ptr<LeaderGatedRayEventExportHandler> gated_ray_event_export_handler_;
+  std::unique_ptr<LeaderGatedRaySyncerHandler> gated_ray_syncer_handler_;
 
   /// Ray Syncer related fields.
   std::unique_ptr<syncer::RaySyncer> ray_syncer_;
diff --git a/src/ray/ray_syncer/ray_syncer.cc b/src/ray/ray_syncer/ray_syncer.cc
index dba8e963cd..06c5c6a050 100644
--- a/src/ray/ray_syncer/ray_syncer.cc
+++ b/src/ray/ray_syncer/ray_syncer.cc
@@ -224,7 +224,7 @@ void RaySyncer::BroadcastMessage(std::shared_ptr<const RaySyncMessage> message)
       "RaySyncer.BroadcastMessage");
 }
 
-ServerBidiReactor *RaySyncerService::StartSync(grpc::CallbackServerContext *context) {
+SyncStreamReactor *RaySyncerService::StartSync(grpc::CallbackServerContext *context) {
   auto reactor = std::make_shared<RayServerBidiReactor>(
       context,
       syncer_.GetIOContext(),
diff --git a/src/ray/ray_syncer/ray_syncer.h b/src/ray/ray_syncer/ray_syncer.h
index c4702f6262..f69b985ae1 100644
--- a/src/ray/ray_syncer/ray_syncer.h
+++ b/src/ray/ray_syncer/ray_syncer.h
@@ -205,12 +205,23 @@ class RaySyncer {
   FRIEND_TEST(SyncerTest, Reconnect);
 };
 
+using SyncStreamReactor =
+    grpc::ServerBidiReactor<RaySyncMessageBatch, RaySyncMessageBatch>;
+
+class RaySyncerStreamHandler {
+ public:
+  virtual ~RaySyncerStreamHandler() = default;
+
+  virtual SyncStreamReactor *StartSync(grpc::CallbackServerContext *context) = 0;
+};
+
 /// RaySyncerService is a service to take care of resource synchronization
 /// related operations.
 /// Right now only raylet needs to setup this service. But in the future,
 /// we can use this to construct more complicated resource reporting algorithm,
 /// like tree-based one.
-class RaySyncerService : public ray::rpc::syncer::RaySyncer::CallbackService {
+class RaySyncerService : public ray::rpc::syncer::RaySyncer::CallbackService,
+                         public RaySyncerStreamHandler {
  public:
   explicit RaySyncerService(
       RaySyncer &syncer,
@@ -221,8 +232,7 @@ class RaySyncerService : public ray::rpc::syncer::RaySyncer::CallbackService {
         auth_token_(std::move(auth_token)),
         auth_token_validator_(auth_token_validator) {}
 
-  grpc::ServerBidiReactor<RaySyncMessageBatch, RaySyncMessageBatch> *StartSync(
-      grpc::CallbackServerContext *context) override;
+  SyncStreamReactor *StartSync(grpc::CallbackServerContext *context) override;
 
  private:
   // The ray syncer this RPC wrappers of.
@@ -235,4 +245,16 @@ class RaySyncerService : public ray::rpc::syncer::RaySyncer::CallbackService {
   ray::rpc::AuthenticationTokenValidator &auth_token_validator_;
 };
 
+class RaySyncerGrpcService : public ray::rpc::syncer::RaySyncer::CallbackService {
+ public:
+  explicit RaySyncerGrpcService(RaySyncerStreamHandler &handler) : handler_(handler) {}
+
+  SyncStreamReactor *StartSync(grpc::CallbackServerContext *context) override {
+    return handler_.StartSync(context);
+  }
+
+ private:
+  RaySyncerStreamHandler &handler_;
+};
+
 }  // namespace ray::syncer

Or should we try to implement the gating in gRPC interceptors?

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.

Discussed offline. The wrapper is still necessary to avoid people adding new method to RaySycnerService and blindly getting the exemption.

Added the change in the latest commit.

@andrewsykim

andrewsykim commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

@jhasm can you do a review?

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 7f2446f. Configure here.

Comment thread src/ray/raylet/node_manager.h Resolved
Comment thread src/ray/gcs/gcs_leader_gated_handlers.h Resolved
Comment thread src/ray/gcs/gcs_server.cc Resolved
Comment thread src/ray/gcs/gcs_leader_gated_handlers.h Resolved
Comment thread src/ray/gcs/gcs_node_manager.cc Outdated
@@ -293,6 +301,10 @@ void GcsNodeManager::HandleGetAllNodeInfo(rpc::GetAllNodeInfoRequest request,
if (iter != alive_nodes_.end()) {
*reply->add_node_info_list() = *iter->second;
++num_added;
} else if (passive_local_node_ != nullptr &&

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 there are a couple issues with how passive_local_node_ is used:

  1. passive_local_node_ does not have mutual exclusion against alive_nodes_ and dead_nodes_. When a query has no state filter, a queried node ID present in both passive_local_node_ and dead_nodes_ will be added once as ALIVE and once as DEAD, returning contradictory states for the same node in a single RPC reply.
  2. passive_local_node_ is never cleared so when promotion occurs and the head node registers into alive_nodes_, it gets counted twice in total_num_nodes - once from alive_nodes_ and once from passive_local_node_
  3. We state in comments that promotion can race with registration - however, checking if (is_leader_fn_()) return; outside mutex_ is a time-of-check to time-of-use race. If promotion occurs between that check and acquiring mutex_ on line 241 in src/ray/gcs/gcs_node_manager.h, promotion finishes active registration, and then this thread acquires the lock and repopulates passive_local_node_, leaving a stale passive cache on an active leader.

I think we should:

  1. In CachePassiveLocalNode: acquire mutex_ before checking is_leader_fn_(), and drop caching if the node is already present in alive_nodes_ or dead_nodes_:
void CachePassiveLocalNode(const rpc::GcsNodeInfo &node_info) {
  RAY_CHECK(node_info.is_head_node())
      << "CachePassiveLocalNode must only cache the local head node.";
  absl::MutexLock lock(&mutex_);
  if (is_leader_fn_()) {
    return;
  }
  NodeID node_id = NodeID::FromBinary(node_info.node_id());
  if (alive_nodes_.contains(node_id) || dead_nodes_.contains(node_id)) {
    return;
  }
  passive_local_node_ = std::make_shared<rpc::GcsNodeInfo>(node_info);
}
  1. In queries (HandleGetAllNodeInfo, GetAllNodeAddressAndLiveness): only inspect passive_local_node_ if !is_leader_fn_() (or provide a ClearPassiveLocalNode() method called during promotion/AddNode).

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.

passive_local_node_ does not have mutual exclusion against alive_nodes_ and dead_nodes_

actually passive_local_node_ will be cleared during promotion, so it should be safe. Though in this pr, I also added the protection before promotion phase . In IsPassiveLocalNode will check if the node exists in alive_nodes or dead_nodes

passive_local_node_ is never cleared so when promotion

It will be cleared in following pr. (The related promotion logic is going to be something like
image
)

outside mutex_ is a time-of-check to time-of-use race

yeah, it could be the real issue. updated

Comment thread src/ray/gcs/gcs_node_manager.h Resolved
Comment thread src/ray/gcs/gcs_server.h Resolved
Comment thread src/ray/gcs/gcs_leader_gated_handlers.h Resolved
Comment thread src/ray/gcs/gcs_node_manager.h Resolved
Comment thread src/ray/gcs/gcs_node_manager.cc Resolved

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

Read through the gating layer, the node-manager passive cache, and the syncer refactor. The macro-per-RPC approach is a good call — it makes each RPC's policy a single auditable line and forces a decision when a new RPC is added. A few things worth addressing before merge, mostly around the passive-node cache lifecycle and member destruction order.

Comment thread src/ray/gcs/gcs_leader_gated_handlers.h Outdated

// Helper macro to send reply status. Wrapped in do/while(0) so the multi-statement
// body behaves as a single statement in any context (e.g. an unbraced if/else).
#define GCS_PROXY_SEND_REPLY(send_reply_callback, reply, status) \

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.

GCS_PROXY_SEND_REPLY has the same body as GCS_RPC_SEND_REPLY in grpc_service_interfaces.h, which this file already includes. Reuse that one (add the do/while(0) wrapper there if you need it) rather than keeping a second copy that can drift.

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.

adopt ryan's suggestion above of using the template #65711 (comment)

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.

oh actually I think your suggestion makes more sense. changed to use GCS_RPC_SEND_REPLY

return;
}
// Cache the local head node in-memory without persisting to Redis
cache_local_node_fn_(node_info);

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.

Passive head-node registration replies OK but never persists, publishes NODE_ADDED, or writes the export event. Does the colocated raylet (or anything subscribed through the un-gated pubsub allowlist) depend on that notification during startup? If it does, the OK reply hides the gap until promotion.

@YoyinZyc YoyinZyc Sep 8, 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.

Passive head-node registration replies OK but never persists

It is intentional for this PR, no db writing before promotion.

Does the colocated raylet (or anything subscribed through the un-gated pubsub allowlist) depend on that notification during startup?

No, it only needs to be registered and periodically checks the liveness of its registered gcs. That's why only limited rpcs are open at passive mode.

Comment thread src/ray/gcs/gcs_leader_gated_handlers.h Resolved
Comment thread src/ray/gcs/gcs_node_manager.h Resolved
Comment thread src/ray/gcs/gcs_node_manager.h Outdated
/// LeaderGatedNodeInfoHandler). Only the head node may be cached.
///
/// \param node_info The local head node info to cache.
void CachePassiveLocalNode(const rpc::GcsNodeInfo &node_info) {

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.

Nothing ever clears passive_local_node_. Once promotion registers the head node through the normal path, the node is in both alive_nodes_ and this cache, so GetAllNodeInfo / GetAllNodeAddressAndLiveness return it twice and total is inflated. Even with promotion deferred to the follow-up, this class should own the invariant — either a ClearPassiveLocalNode() called from the register path, or have the readers skip the cache when alive_nodes_ already contains the id.

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.

It is part of the promotion logic which is going to be handled in the following pr. It was in my previous large pr image

Comment thread src/ray/gcs/gcs_node_manager.cc Resolved
Comment thread src/ray/gcs/gcs_server.h Resolved
Comment thread src/ray/gcs/gcs_server.h Resolved
Comment thread src/ray/gcs/gcs_server.h
// Leader-gated proxy handlers. Each wraps the real service handler and, on a
// passive GCS, rejects that service's mutating RPCs. They are owned here so they
// outlive the GrpcServices that reference them. See RegisterRpcServices().
std::unique_ptr<LeaderGatedNodeInfoHandler> gated_node_info_handler_;

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.

Lifetime ordering: rpc_server_ is declared above these (line 287), so it is destroyed last and all the gated handlers plus ray_syncer_service_ are destroyed first — the opposite of what the comment asserts. Previously each service object was owned by rpc_server_ so the ordering was safe. Related: Stop() resets ray_syncer_ before rpc_server_.Shutdown() and never resets ray_syncer_service_. Either declare rpc_server_ last, or reset these explicitly in Stop() after Shutdown().

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.

I am not good at it so please correct me if I am wrong.

I think the teardown ordering here is pre-existing, the existing managers(like gcs_node_manager_) are declared before rpc_server_ and they are not reset explicitly. They are not owned by the rpc_server_ though. The reason it's safe (and has always been safe) is that the Shutdown() in Stop() cancels the server and joins all gRPC threads, so once it returns nothing can invoke a GrpcService anymore. After that, the order in which handlers are destroyed doesn't matter — no thread dereferences them. And I think the gated wrappers don't change this.

But there are 3 special cases, ray_syncer, observability_pubsub_handler_ and pubsub_handler_ are deliberately reset before shutdown. Technically, they should be reset after rpc_server_ IIUC. I tracked the commit history and seems that they are all historical issues, like fixing flaky test. They are safe because StopAllDedicatedIOContexts(); happens ahead and the server is marked as non-serving.

So basically I think it is an issue out of the scope of this pr and the gated wrapper does not introduce any new risk. I clarified the comment and let me know if you think we should fix the existing order(moving all reset() after shutdown()) in this pr.

Comment thread src/ray/raylet/node_manager.h Resolved
Add gcs_leader_gated_handlers.h: per-service proxy handlers that wrap the
real GCS service handlers and, when the GCS is not the active leader, reject
write RPCs with Status::GcsPassive() while forwarding bootstrap/read RPCs.

Boilerplate is collapsed via GCS_GATED_RPC / GCS_ALLOWED_RPC macros so each
RPC's gated-or-allowed status is one explicit, auditable line, and adding a
new RPC to a service is a compile-time-enforced one-liner.

This commit only adds the header (wired into gcs_server_lib); it is not yet
used by the server, so behavior is unchanged.

Signed-off-by: Yuchen Zhou <[email protected]>
…e to GcsNodeManager

Inject an is_leader_fn into GcsNodeManager (default [](){return true;} so
existing callers and single-head clusters are unchanged) and report it in
HandleCheckAlive via reply->set_is_leader(is_leader_fn_()).

Add an in-memory passive_local_node_ cache: CachePassiveLocalNode() records
the local head node's registration while passive (without writing to storage).
CheckAlive / GetAllNodeInfo / GetAllNodeAddressAndLiveness / IsNodeAlive
account for this cached node so the local head is visible while the GCS is
passive.

Gating of the write RPCs is wired up in a later commit; on its own this commit
preserves existing behavior (is_leader defaults to true, passive_local_node_ is
never set).

Signed-off-by: Yuchen Zhou <[email protected]>
… gating

Move every rpc_server_.RegisterService(...) call out of the individual InitXxx
methods into one centralized GcsServer::RegisterRpcServices(), invoked from
DoStart after all managers/handlers are constructed. This makes the
gated-vs-exempt decision for each service explicit and auditable in a single
place, and forces any new GCS service to be added here (hard to forget to gate
a new mutating service).

Each gated service's real handler is wrapped via the MaybeGate() template, which
installs the corresponding LeaderGated* proxy and binds it to IsLeader(). When
leader election is disabled (GcsServerConfig::ray_leader_elect_enabled defaults
to false), is_leader_ is initialized to true and IsLeader() is always true, so
every RPC is forwarded unchanged -- behavior is identical to before.

RaySyncer is intentionally registered without gating (documented in
RegisterRpcServices): it is an in-memory resource-view stream needed for a warm
passive standby and has no leader-only side effects.

Adds GcsServerConfig::ray_leader_elect_enabled, GcsServer::IsLeader(),
the MaybeGate template, is_leader_, and the gated_* handler members. Promotion
that flips is_leader_ to true is wired up in a later PR.

Signed-off-by: Yuchen Zhou <[email protected]>
YoyinZyc and others added 4 commits September 8, 2026 20:00
… manager

Add gcs_leader_gated_handlers_test.cc: unit tests for every LeaderGated* proxy,
verifying that mutating RPCs are rejected with Status::GcsPassive() when not the
leader and that bootstrap/read RPCs are always forwarded.

Extend gcs_node_manager_test.cc: cover HandleCheckAlive leadership reporting, the
passive_local_node_ cache visibility in CheckAlive/GetAllNodeInfo/
GetAllNodeAddressAndLiveness, and PromoteNodeManager (including stale head
cleanup).

Extend gcs_client_test.cc TestGcsClientCheckAlive: assert Nodes().IsGcsLeader()
is true after CheckAlive against a normal (non-leader-elect) GCS, guarding the
client-side leadership cache fed by the server's is_leader reply.

The end-to-end passive-server / promotion RPC tests from the original change
depend on the deferred-loading promotion path and are deferred to the PR that
introduces it.

Signed-off-by: Yuchen Zhou <[email protected]>
Split RaySyncerService into a stream handler interface (RaySyncerStreamHandler),
its concrete implementation (RaySyncerService), and a gRPC adapter
(RaySyncerGrpcService). This lets the GCS register the syncer stream through the
same MaybeGate/LeaderGated proxy pattern as the other services, instead of being
a one-off exemption.

StartSync remains *allowed* on a passive GCS: it is a side-effect-free in-memory
resource-view stream whose passive-vs-active scope is already enforced upstream at
node registration. The proxy exists so any future RPC added to the service must
explicitly choose its own leader policy rather than silently inheriting the
exemption.

The raylet registers the same gRPC adapter directly (no gating; it has no leader
concept). GCS creates the real handler in InitRaySyncer() and only registers it in
RegisterRpcServices(), matching the other services' Init/Register split.

Tested: ray_syncer_test, gcs_leader_gated_handlers_test (now covers the RaySyncer
allow-on-passive contract), gcs_node_manager_test, node_manager_test all pass;
multi-node Python smoke test confirms cross-node resource-view sync end-to-end.
AI assistance was used.

Signed-off-by: Yuchen Zhou <[email protected]>
- Guard passive_local_node_ with ABSL_GUARDED_BY(mutex_) and check the leader
  state under mutex_ in CachePassiveLocalNode to close the TOCTOU race.
- De-duplicate the passive local node against alive_nodes_/dead_nodes_ on both
  the write and read paths so it is never double-counted or reported with a
  contradictory state; add IsPassiveLocalNode()/HasSurfaceablePassiveLocalNode()
  and node_matches_request_filters() helpers to remove the copied checks.
- Add ClearPassiveLocalNode() (used by tests now; wired into promotion later).
- Drop the dead passive branch from IsNodeAlive() and verify the passive cache
  through the real visibility RPCs instead.
- Add TestCachePassiveLocalNodeSkipsWhenPromoted and related passive-visibility
  tests.

AI assistance was used to prepare this change.

Signed-off-by: Yuchen Zhou <[email protected]>
@YoyinZyc
YoyinZyc force-pushed the passive_gcs_gating branch 2 times, most recently from d31b817 to b30ed16 Compare September 10, 2026 00:24
…ion is disabled

- In MaybeGate(), return the real handler directly when
  ray_leader_elect_enabled is false, eliminating proxy allocation, extra
  virtual dispatch, and std::function invocations on every RPC in non-HA
  mode.
- Replace GCS_PROXY_SEND_REPLY macro with existing GCS_RPC_SEND_REPLY in
  grpc_service_interface.h.
- Update documentation comments to clarify MaybeGate semantics.
- Move ray_syncer and ray_syncer_service_ declaration before rpc_server
  in node_manager.h.

Signed-off-by: Yuchen Zhou <[email protected]>
@YoyinZyc

Copy link
Copy Markdown
Contributor Author

@ryanaoleary @jhasm I hope I replied all your comments. Please take another look of the most 2 recent commits and let me know if I miss anything. Thank you for the review!!

@rueian

rueian commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

ping @jhasm

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

👍 LGTM

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

LGTM!

@ryanaoleary

Copy link
Copy Markdown
Contributor

@rueian for merge

@rueian
rueian merged commit 9634fa7 into ray-project:master Sep 15, 2026
6 checks passed
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ion RPC gating (ray-project#65711)

## Description

This is the C++ RPC-gating layer for the Active-Passive GCS feature
(split from the larger ray-project#64422, following the interface PR ray-project#65132). It
adds the server-side mechanism that, when a GCS is **not** the active
leader, rejects mutating RPCs with `Status::GcsPassive()` while
forwarding bootstrap/read RPCs. Everything is gated behind
`LEADER_ELECT`, which **defaults to off**, so a normal single-GCS
cluster behaves exactly as before.

This PR intentionally contains **only the gating mechanism**. The
deferred-loading / promotion lifecycle (which flips a GCS from passive
to active, updates the `is_leader` and the clears the
`passive_local_node_`) and the end-to-end passive-head startup are in a
follow-up PR. Since the gcs hasn't connected with the leader election
model, setting `LEADER_ELECT` will not have gcs leader election
behavior.

AI assistance was used to prepare this change.

## Issue

ray-project#63643

## High-level changes

| Area | Change |
| :--- | :--- |
| **Leader-gated proxy handlers** | New gcs_leader_gated_handlers.h: a
per-service proxy (`LeaderGated*Handler`) that wraps each real GCS
service handler. `GCS_GATED_RPC` / `GCS_ALLOWED_RPC` macros make each
RPC's gated-or-allowed status a single, auditable line; adding a new RPC
to a service is a compile-time-enforced one-liner. |
| **GcsNodeManager leadership + passive cache** | Injects an
`is_leader_fn` (defaults to `[]{return true;}`), reports it in
`HandleCheckAlive` via `reply->set_is_leader(...)`, and adds an
in-memory `passive_local_node_` cache (`CachePassiveLocalNode`) so the
local head node is visible while passive and flushed through the normal
RegisterNode path on promotion. |
| **Centralized service registration** | All 14
`rpc_server_.RegisterService(...)` calls are moved out of the individual
`InitXxx()` methods into one `GcsServer::RegisterRpcServices()`, called
from `DoStart` after all managers are constructed. Gated services go
through `MaybeGate`; `RaySyncer` is registered in an explicit
"intentionally NOT gated" section with a documented rationale. |

## Test plan

**Unit (C++)** — new
- `gcs_leader_gated_handlers_test.cc`
- `gcs_node_manager_test.cc` 
-  `gcs_client_test.cc`

**Integration / backward-compat (C++)** — existing
- `gcs_server_rpc_test` 

**Real-cluster smoke (default config, `LEADER_ELECT` off)**
- ensure backward compatibility

---------

Signed-off-by: Yuchen Zhou <[email protected]>
Signed-off-by: Rueian <[email protected]>
Co-authored-by: Rueian <[email protected]>
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 core Issues that should be addressed in Ray Core go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants