Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements active-passive leader election for GCS high availability, allowing GCS servers to boot in passive mode and gating mutating RPCs. It updates the dashboard head, agent, log monitor, and autoscaler to suppress periodic tasks and defer registrations when GCS is passive, while exposing new readiness endpoints. The review feedback identifies a critical race condition in the dashboard startup check, a lifecycle issue where the GCS liveness task in the agent is cancelled prematurely (stalling leadership updates for readiness probes), and a missing null check in the log monitor's error path.
2a31431 to
7dca94d
Compare
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
| std::unique_ptr<LeaderGatedPlacementGroupInfoHandler> | ||
| gated_placement_group_info_handler_; | ||
| std::unique_ptr<LeaderGatedAutoscalerStateHandler> gated_autoscaler_state_handler_; | ||
| std::unique_ptr<LeaderGatedInternalKVHandler> gated_internal_kv_handler_; |
There was a problem hiding this comment.
Hi @YoyinZyc, thanks for the PR, but I found that the changes for gating RPCs and leader status checks are spread around the GcsServer and GcsNodeManager. I am afraid that the current approach is not cohesive enough and can be hard to maintain in the long term.
Is it possible that we put all gating into a new GcsServer that implements all RPC handlers and proxies to the embedded real GcsServer, and keep the real one mostly intact?
There was a problem hiding this comment.
yeah I put most of the rpc gating logic in gcs_leader_gated_handlers.h. Just added the macro to make it simpler and moved some HandleRegisterNode from the gcs_node_manager to here.
But for other logics, it would be hard to move and isolate from the existing code especially for some gcs initialization logic. I tried to leave as little footprint as possible and make sure the everything is guarded by feature flag.
Please let me know if there is anything you think I can refactor.
There was a problem hiding this comment.
Yes, gcs_leader_gated_handlers.h is more cohesive, but my concern is how we can avoid a situation where someone introduces a new GCS API but forgets to make it gated. Currently the grpc service registrations rpc_server_.RegisterService() are scattered in the GcsServer, and it seems pretty easy for someone to bypass the MaybeGate in the future when that one introduces a new grpc service.
I wonder if it is possible to move rpc_server_ one level up and have a clearer branch doing service registrations, for example:
if (active_passive_enabled) {
gated_server.Register(rpc_server_)
} else {
gcs_server.Register(rpc_server_)
}
There was a problem hiding this comment.
BTW, is RaySyncerService intentionally not gated?
Signed-off-by: Yuchen Zhou <[email protected]>
…eferred loading. Signed-off-by: Yuchen Zhou <[email protected]>
…centralized leader-gated service proxies Signed-off-by: Yuchen Zhou <[email protected]>
…et registration Signed-off-by: Yuchen Zhou <[email protected]>
Signed-off-by: Yuchen Zhou <[email protected]>
…te readiness from liveness probes - Introduce C++ IsGcsLeader query and cache it in NodeInfoAccessor. - Expose is_gcs_leader binding to Python InnerGcsClient. - Distinguish GCS liveness checking from GCS active leadership (readiness) checking in the Dashboard health checker. - Add /api/gcs_readiness endpoint to query GCS active leadership status. This supports separating liveness and readiness fallback exec probes when HTTP probes are disabled in KubeRay. - Support "readiness=true" query parameter in the unified /api/healthz endpoint. Signed-off-by: Yuchen Zhou <[email protected]>
active-passive GCS. Signed-off-by: Yuchen Zhou <[email protected]>
…date unit tests. Restrict the RPCs on passive head. Signed-off-by: Yuchen Zhou <[email protected]>
…etry loops in Python services Signed-off-by: Yuchen Zhou <[email protected]>
…de (monitor, log_monitor, usage_stats) Signed-off-by: Yuchen Zhou <[email protected]>
Signed-off-by: Yuchen Zhou <[email protected]>
…ed leadership status. This method will be applied to the process that has already had the async_check_alive running on the background, like dashboard_head or usage_stats_head. For other modules like autoscaler, they need to call is_gcs_leader explicitly to fetch the status. Also add a new status code for GCS passive head unavailable. Signed-off-by: Yuchen Zhou <[email protected]>
… logic from gcs_node_manager.cc to the centralized gcs_leader_gated_handlers.h. Also added the macro to simplify the gated file. Signed-off-by: Yuchen Zhou <[email protected]>
401e073 to
af22f8d
Compare
gcs_server. Signed-off-by: Yuchen Zhou <[email protected]>
af22f8d to
b656e40
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Reviewed by Cursor Bugbot for commit b656e40. Configure here.
| if is_leader_elect_enabled and not is_passive: | ||
| # After a grace period of 2 seconds, check if GCS is actually passive. | ||
| # This avoids the race condition where active GCS is just slow to respond on startup. | ||
| if time.time() - start_time_s >= 2.0: |
There was a problem hiding this comment.
prefer to make this a constant rather than hard-coding the 2.0 timeout value
| gcs_client=self.gcs_client, | ||
| ) | ||
| except ValueError as e: | ||
| if "passive" in str(e).lower(): |
There was a problem hiding this comment.
several times we do this pattern of string matching the exception which seems brittle, Gemini suggests adding a GcsPassiveError(ValueError) exception class in common.pxi which seems like a more robust solution
| ) | ||
| finally: | ||
| if self._gcs_check_alive_task: | ||
| self._gcs_check_alive_task.cancel() |
There was a problem hiding this comment.
rather than unconditionally canceling the alive task here, we can check:
if not self._gcs_check_alive_task.done()
self._gcs_check_alive_task.cancel()
since cancel() is not required if done() == True
| assert str(dashboard_port_B).encode() not in autoscaler_metrics_in_kv | ||
|
|
||
| # Verify job submission behavior | ||
| # 1. Job submission to Node A (Active Head) should succeed |
There was a problem hiding this comment.
Can we add a test case where the active head (node A) dies, the active head changes (node B is promoted), and that job submission then works from the new active head
| def mock_sleep(seconds): | ||
| raise SentinelException("Loop active run finished") | ||
|
|
||
| import ray._private.log_monitor as log_monitor_module |
There was a problem hiding this comment.
try to keep imports at the top of the file unless it's required that they're inline for the code to work
| # Enable leader election config | ||
| monkeypatch.setattr(ray_constants, "RAY_LEADER_ELECT", True) | ||
|
|
||
| def mock_sleep(seconds): |
There was a problem hiding this comment.
Rather than mocking sleep here in order to interrupt the iteration after one step, can we create a helper function like step_once() that extracts the inner logic of log_monitor.run() that we can then call here
That way we avoid this pattern of mocking sleep and raising a SentinelException several times across the tests
|
|
||
| def test_usage_stats_head_passive_suppression(monkeypatch): | ||
| """Verify that UsageStatsHead suppresses telemetry reports in passive mode.""" | ||
| mock_gcs_client = types.SimpleNamespace() |
There was a problem hiding this comment.
nit: we do mock_gcs_client = types.SimpleNamespace() several times and then set is_gcs_leader_local, I think it'd be cleaner to add a FakeGcsClient class with explicit properties (i.e. we can do: client.set_gcs_leader(False)) to avoid this boilerplate across multiple tests
|
This PR is quite large and it may be easier to review/merge it if the Proto changes, C++ scheduler changes, and Python side logic can be split into separate PRs. |
Sorry for a big PR, it was big to pass the manual test. Will try to break it down into smaller ones and address the above comments. |
…ion interface (protocol, status, client cache) (#65132) ## Description This is the foundational, interface-only PR for the Active-Passive GCS feature (split from the larger #64422). It introduces the wire-protocol field, status code, config flag, and client-side leadership-caching plumbing — all feature-gated behind `LEADER_ELECT` / `RAY_LEADER_ELECT`, which **defaults to OFF**. No server-side passive behavior is included here; this PR is pure additive scaffolding that later PRs build on. ## Issue #63643 ## High-level changes | Layer | Change | | :--- | :--- | | **Protocol** | Add `optional bool is_leader = 4` to `CheckAliveReply`. Marked `optional` so a new client can distinguish "field absent" (an old GCS during a rolling upgrade) from an explicit `false`. | | **Status** | New `StatusCode::GcsPassive` (38) with `Status::GcsPassive()` and `IsGcsPassive()`, registered in the code↔string maps. No code path returns it yet. | | **Config** | New `RAY_CONFIG(bool, LEADER_ELECT, false)` (C++) and matching `ray_constants.RAY_LEADER_ELECT` (Python), kept in sync via the `RAY_LEADER_ELECT` env var. | | **C++ client** | `NodeInfoAccessor` caches an `atomic<bool> is_gcs_leader_`, updated from each `CheckAlive` reply (`has_is_leader() ? is_leader() : true` — absence is treated as the legacy leader). Exposes `IsGcsLeader()`. When `LEADER_ELECT` is off, it initializes to `true` and never changes (legacy behavior). The test-only default constructor sets `client_impl_ = nullptr`. | | **Python bindings** | `GcsClient.is_gcs_leader_local()` (reads the cache) and `is_gcs_leader()` (triggers a `CheckAlive`, then reads the cache). Both return `True` when `RAY_LEADER_ELECT` is off. `check_status` maps `GcsPassive → RpcError(UNAVAILABLE)`. | ## Behavior change / backward compatibility - **With `LEADER_ELECT` off (the default): zero observable change.** `is_gcs_leader()` / `is_gcs_leader_local()` always return `True`; the `GcsPassive` status code and the `is_leader` field are never produced. - **Wire compatibility:** the new proto field is `optional` and defaults to absent, so old/new clients and servers interoperate during rolling upgrades (absence = legacy leader). - **No public API signatures change**; all additions are new symbols. ## Test plan **Unit (C++)** — accessor_test.cc - `TestIsGcsLeaderCaching` — cache defaults to `true`; `store`/`load` behave correctly. - `TestLeaderElectionDisabledByDefault` — with `LEADER_ELECT` off, the accessor always reports itself as leader regardless of any `is_leader` value (rolling-upgrade / legacy guard). - Command: `bazel test //src/ray/gcs_rpc_client/tests:accessor_test` → **PASS** **Integration (Python)** — test_gcs_utils.py - `test_is_gcs_leader_defaults` — default path: both methods return `True`; and in a spawned subprocess with `RAY_LEADER_ELECT=true`, `is_gcs_leader_local()` starts as `False` (client-side cache init). The cross-layer server assertion is intentionally deferred to a later PR. - Command: `python -m pytest python/ray/tests/test_gcs_utils.py::test_is_gcs_leader_defaults` → **PASS** --------- Signed-off-by: Yuchen Zhou <[email protected]>
…ion interface (protocol, status, client cache) (ray-project#65132) ## Description This is the foundational, interface-only PR for the Active-Passive GCS feature (split from the larger ray-project#64422). It introduces the wire-protocol field, status code, config flag, and client-side leadership-caching plumbing — all feature-gated behind `LEADER_ELECT` / `RAY_LEADER_ELECT`, which **defaults to OFF**. No server-side passive behavior is included here; this PR is pure additive scaffolding that later PRs build on. ## Issue ray-project#63643 ## High-level changes | Layer | Change | | :--- | :--- | | **Protocol** | Add `optional bool is_leader = 4` to `CheckAliveReply`. Marked `optional` so a new client can distinguish "field absent" (an old GCS during a rolling upgrade) from an explicit `false`. | | **Status** | New `StatusCode::GcsPassive` (38) with `Status::GcsPassive()` and `IsGcsPassive()`, registered in the code↔string maps. No code path returns it yet. | | **Config** | New `RAY_CONFIG(bool, LEADER_ELECT, false)` (C++) and matching `ray_constants.RAY_LEADER_ELECT` (Python), kept in sync via the `RAY_LEADER_ELECT` env var. | | **C++ client** | `NodeInfoAccessor` caches an `atomic<bool> is_gcs_leader_`, updated from each `CheckAlive` reply (`has_is_leader() ? is_leader() : true` — absence is treated as the legacy leader). Exposes `IsGcsLeader()`. When `LEADER_ELECT` is off, it initializes to `true` and never changes (legacy behavior). The test-only default constructor sets `client_impl_ = nullptr`. | | **Python bindings** | `GcsClient.is_gcs_leader_local()` (reads the cache) and `is_gcs_leader()` (triggers a `CheckAlive`, then reads the cache). Both return `True` when `RAY_LEADER_ELECT` is off. `check_status` maps `GcsPassive → RpcError(UNAVAILABLE)`. | ## Behavior change / backward compatibility - **With `LEADER_ELECT` off (the default): zero observable change.** `is_gcs_leader()` / `is_gcs_leader_local()` always return `True`; the `GcsPassive` status code and the `is_leader` field are never produced. - **Wire compatibility:** the new proto field is `optional` and defaults to absent, so old/new clients and servers interoperate during rolling upgrades (absence = legacy leader). - **No public API signatures change**; all additions are new symbols. ## Test plan **Unit (C++)** — accessor_test.cc - `TestIsGcsLeaderCaching` — cache defaults to `true`; `store`/`load` behave correctly. - `TestLeaderElectionDisabledByDefault` — with `LEADER_ELECT` off, the accessor always reports itself as leader regardless of any `is_leader` value (rolling-upgrade / legacy guard). - Command: `bazel test //src/ray/gcs_rpc_client/tests:accessor_test` → **PASS** **Integration (Python)** — test_gcs_utils.py - `test_is_gcs_leader_defaults` — default path: both methods return `True`; and in a spawned subprocess with `RAY_LEADER_ELECT=true`, `is_gcs_leader_local()` starts as `False` (client-side cache init). The cross-layer server assertion is intentionally deferred to a later PR. - Command: `python -m pytest python/ray/tests/test_gcs_utils.py::test_is_gcs_leader_defaults` → **PASS** --------- Signed-off-by: Yuchen Zhou <[email protected]> Signed-off-by: 400Ping <[email protected]>
|
Since this PR is going to be split into small parts, let's close it. |
…ion RPC gating (#65711) ## 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 --------- Signed-off-by: Yuchen Zhou <[email protected]> Signed-off-by: Rueian <[email protected]> Co-authored-by: Rueian <[email protected]>
…66222) ## Description Third slice of the Phase 2 split of #64422. Earlier slices landed the passive interface (proto / `StatusCode::GcsPassive` / config / client) and the server-side RPC gating. This PR focuses on the passive GCS lifecycle including cold start and promotion. Everything is behind `RAY_ENABLE_GCS_LEADER_ELECTION`, **default off**. Please note that the gcs has not connected to the elector. There is no caller to trigger the promotion yet. <img width="836" height="953" alt="image" src="https://github.com/user-attachments/assets/7afd55fc-796e-401f-9f0c-e15c4224e296" /> ## Key changes **1. Passive boot — `gcs_server.{h,cc}`** - Skip the GCS table load and every shared-storage write. Resolve only the cluster ID and start the RPC server, so health checks and the un-gated (visibility) RPCs work while passive. Table loading moves to promotion. - `GetOrGenerateClusterId()` is restructured into three explicit branches; the new one is "no cluster ID yet **and** passive" → wait for the leader to write it (1s retry, rate-limited log) instead of minting one. - The GCS-pid and autoscaler-v2-flag `Put()`s are extracted into `WriteGcsPid()` / `WriteAutoscalerV2Flag()`, still called inline when leader election is off. - `RecordMetrics()` and the startup metrics-exporter init move into `StartMetricsReporting()`, now active-only: `RecordMetrics()` writes actor and placement-group usage counters to shared storage, and a passive GCS (empty tables) would overwrite the leader's counts with zeroes — a GCS-initiated write that RPC gating cannot catch. `PrintDebugState()` keeps running while passive so a standby is not dark. **2. Head-node handover — `gcs_node_manager.{h,cc}`** - `PromoteNodeManager()` replays the head node cached in `passive_local_node_` through the real `HandleRegisterNode` path, so it is persisted, publishes `NODE_ADDED`, and — because head registration marks every alive head dead — retires the stale head hydrated from storage. Without it the cluster reports two live heads after a failover. - `ClearPassiveLocalNode()` → `GetPassiveLocalNode()`: the cache is read, not taken, and released from the registration callback once `alive_nodes_` tracks the node. Taking it up front left the head in neither place while two chained storage writes completed (the stale head's DEAD record, then its own), so the un-gated visibility RPCs reported no live head mid-handover. The member is a `std::optional` — it is a value that may be absent, and nothing hands a pointer to it out past `mutex_`. - `CachePassiveLocalNode()` → `TryHandlePassiveHeadRegistration()`, returning whether the registration was handled. The gated handler used to reply `OK` unconditionally; if promotion landed between its `!is_leader_fn_()` check and the cache write, the node was neither cached nor registered, and the raylet never retries an `OK`. On`false` the handler now falls through to the real `HandleRegisterNode`. **3. `GcsServer::PromoteToLeader()`** - Loads the tables, `HydrateManagers()`, flips `is_leader_`, promotes the node manager, `WriteActiveOnlyKeys()`, `StartMetricsReporting()`. - Order is load-bearing: flipping `is_leader_` earlier serves mutating RPCs against half-loaded state; promoting the node manager earlier registers the local head before the stale one is loaded, leaving two live heads. - `HydrateManagers()` covers every manager, in `DoStart()`'s order, because `GcsNodeManager::Initialize()` no longer notifies the node-added listeners. Relying on that fan-out was wrong twice over: `Postable::Post` enqueues rather than runs inline, so `GcsPlacementGroupManager::Initialize()` scheduled its pending groups against a zero-node resource view, and the previous leader's head reached the listener's metrics branch and took the one-shot `metrics_exporter_initialized_` latch with a remote agent port. Suppressing the fan-out is a no-op for `DoStart()`, where the listener list is still empty at that point. - Guarded on `IsLeader() || promotion_started_` — neither alone is enough, and a second load would hydrate twice (`GcsJobManager` bumps a per-job reference count that would never drop back to zero). - Promotion arriving while `Start()` is parked on the cluster-ID wait just flips `is_leader_`: that wait only ends when a leader writes the ID, and that leader is now us. The continuation then boots active and runs `WriteActiveOnlyKeys()`. **4. Flag wiring — `gcs_server_main.cc`** - Assign `GcsServerConfig::enable_gcs_leader_election` from `RayConfig::ENABLE_GCS_LEADER_ELECTION()` (env `RAY_ENABLE_GCS_LEADER_ELECTION`). Nothing assigned it before, so the passive/promotion paths were unreachable. - Field renamed `ray_leader_elect_enabled` → `enable_gcs_leader_election` (internal struct field only) so the feature greps as one name. - Loud startup `WARNING`: no production caller drives promotion yet, so a lone head with the flag set parks on the cluster-ID wait. Better an explicit warning than something that looks like a hang. The warning goes away once the elector lands. ## Tests ### Unit — `//src/ray/gcs/tests:gcs_node_manager_test` Exercises `GcsNodeManager` in isolation (no server, no Redis), pinning the head-node cache semantics independently of how promotion is driven. | Test | What it guards | | :--- | :--- | | `TestPromoteRegistersCachedHeadAndKillsStaleHead` | The head cached while passive becomes a real alive node on promotion, the stale head is marked dead, and a second promotion registers nothing again. | | `TestPromoteIsNoopWithoutCachedHead` | The default (leader-election-off) path, where nothing was ever cached, must not invent a registration. | | `TestPassiveHeadRegistrationSkipsWhenPromoted` | Registration is async, so this covers the window after promotion but before `alive_nodes_` is populated. The head promotion is registering is reported handled; any other head is not, so the caller registers it instead of dropping it. | | `TestHeadStaysVisibleDuringPromotionHandover` | Mid-handover, with the stale head already retired and the storage write still in flight, CheckAlive and the alive-head query must already answer with the promoted head. | | `TestInitializeDoesNotNotifyNodeAddedListeners` | Initialize() restores the cache without emitting node-added events, which is what lets HydrateManagers() feed the downstream managers itself. | ### `//src/ray/gcs/tests:gcs_leader_gated_handlers_test` Extended `TestNodeRegistrationAndGating`: when the cache reports the registration was not handled, the proxy must fall through to the real handler instead of replying OK. | ### Integration — `//src/ray/gcs/tests:gcs_server_rpc_test` Real `GcsServer` processes against a real Redis over real gRPC. Two heads with leader election enabled is the only topology a production cluster produces, so `GcsLeaderElectionTestBase` starts no GCS of its own and `GcsLeaderElectionTest` adds one promoted leader. | Test | What it guards | | :--- | :--- | | `TestPassiveServerReadiness` | A passive GCS adopts the leader's cluster ID, serves health checks, and reports `is_leader=false` over `CheckAlive`. | | `TestColdStartPromotionBootsWinnerAndLoser` | A cluster coming up for the first time: two candidates park against empty storage writing nothing; promoting one releases its own cluster-ID wait instead of deadlocking, writes the three keys, and thereby unblocks the other, which adopts the same ID and stays passive. | | `TestPromotionActivatesTheServer` | Before promotion a passive GCS cannot see a node the leader persisted and rejects RegisterNode with GcsPassive; after promotion it serves that node from storage, reports its resources through GetAllTotalResources (the resource manager is hydrated, not just the node table), and accepts the same registration. | | `TestPromotionHandsOverTheHeadNode` | The head handover a failover comes down to: the cached local head reaches storage only at promotion, the head it replaces is retired, and exactly one head stays alive. | | `TestPromotionRewritesActiveOnlyKeys` | A promoted GCS updates the GCS pid and autoscaler-v2 flag rather than leaving the previous leader's values. | | `TestPromotionIsIdempotent` | The elector re-invokes `on_started_leading`; both calls are issued from one handler so the second also lands while the first is still loading tables. | ### Manual — the legacy path is untouched No unit test covers `main()`, and the point of this PR is that a normal cluster does not notice it, so the default path was exercised on a real cluster with the flag unset. Both entry points were checked because `ray.init()` and `ray start --head` reach `gcs_server_main.cc` differently. Via `ray.init()`: - the flag defaults to `False` and the env var is unset - tasks and actors run normally - one alive node, which is the driver's node; reading the GCS node table directly shows exactly one alive `is_head_node` - `gcs_pid` and `__autoscaler_v2_enabled` are both present in the KV store at startup, confirming the extracted writes still happen inline - `is_gcs_leader()` and `is_gcs_leader_local()` both return `True` - `gcs_server.out` contains no leader-election lines at all and logs normal cluster-ID generation - clean `ray.shutdown()` Via `ray start --head`: the cluster starts, `ray status` reports the node active with full resources, the GCS log again shows no leader-election lines, and `ray stop` leaves no stray processes. With the flag **on**, the same binary logs the experimental warning, starts passive, and parks on the cluster-ID wait without ever writing one, because the leader election lib has not been integrated yet. ## Related issues #63643 ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Yuchen Zhou <[email protected]>
…ion interface (protocol, status, client cache) (ray-project#65132) ## Description This is the foundational, interface-only PR for the Active-Passive GCS feature (split from the larger ray-project#64422). It introduces the wire-protocol field, status code, config flag, and client-side leadership-caching plumbing — all feature-gated behind `LEADER_ELECT` / `RAY_LEADER_ELECT`, which **defaults to OFF**. No server-side passive behavior is included here; this PR is pure additive scaffolding that later PRs build on. ## Issue ray-project#63643 ## High-level changes | Layer | Change | | :--- | :--- | | **Protocol** | Add `optional bool is_leader = 4` to `CheckAliveReply`. Marked `optional` so a new client can distinguish "field absent" (an old GCS during a rolling upgrade) from an explicit `false`. | | **Status** | New `StatusCode::GcsPassive` (38) with `Status::GcsPassive()` and `IsGcsPassive()`, registered in the code↔string maps. No code path returns it yet. | | **Config** | New `RAY_CONFIG(bool, LEADER_ELECT, false)` (C++) and matching `ray_constants.RAY_LEADER_ELECT` (Python), kept in sync via the `RAY_LEADER_ELECT` env var. | | **C++ client** | `NodeInfoAccessor` caches an `atomic<bool> is_gcs_leader_`, updated from each `CheckAlive` reply (`has_is_leader() ? is_leader() : true` — absence is treated as the legacy leader). Exposes `IsGcsLeader()`. When `LEADER_ELECT` is off, it initializes to `true` and never changes (legacy behavior). The test-only default constructor sets `client_impl_ = nullptr`. | | **Python bindings** | `GcsClient.is_gcs_leader_local()` (reads the cache) and `is_gcs_leader()` (triggers a `CheckAlive`, then reads the cache). Both return `True` when `RAY_LEADER_ELECT` is off. `check_status` maps `GcsPassive → RpcError(UNAVAILABLE)`. | ## Behavior change / backward compatibility - **With `LEADER_ELECT` off (the default): zero observable change.** `is_gcs_leader()` / `is_gcs_leader_local()` always return `True`; the `GcsPassive` status code and the `is_leader` field are never produced. - **Wire compatibility:** the new proto field is `optional` and defaults to absent, so old/new clients and servers interoperate during rolling upgrades (absence = legacy leader). - **No public API signatures change**; all additions are new symbols. ## Test plan **Unit (C++)** — accessor_test.cc - `TestIsGcsLeaderCaching` — cache defaults to `true`; `store`/`load` behave correctly. - `TestLeaderElectionDisabledByDefault` — with `LEADER_ELECT` off, the accessor always reports itself as leader regardless of any `is_leader` value (rolling-upgrade / legacy guard). - Command: `bazel test //src/ray/gcs_rpc_client/tests:accessor_test` → **PASS** **Integration (Python)** — test_gcs_utils.py - `test_is_gcs_leader_defaults` — default path: both methods return `True`; and in a spawned subprocess with `RAY_LEADER_ELECT=true`, `is_gcs_leader_local()` starts as `False` (client-side cache init). The cross-layer server assertion is intentionally deferred to a later PR. - Command: `python -m pytest python/ray/tests/test_gcs_utils.py::test_is_gcs_leader_defaults` → **PASS** --------- Signed-off-by: Yuchen Zhou <[email protected]>
…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]>
…ay-project#66222) ## Description Third slice of the Phase 2 split of ray-project#64422. Earlier slices landed the passive interface (proto / `StatusCode::GcsPassive` / config / client) and the server-side RPC gating. This PR focuses on the passive GCS lifecycle including cold start and promotion. Everything is behind `RAY_ENABLE_GCS_LEADER_ELECTION`, **default off**. Please note that the gcs has not connected to the elector. There is no caller to trigger the promotion yet. <img width="836" height="953" alt="image" src="https://github.com/user-attachments/assets/7afd55fc-796e-401f-9f0c-e15c4224e296" /> ## Key changes **1. Passive boot — `gcs_server.{h,cc}`** - Skip the GCS table load and every shared-storage write. Resolve only the cluster ID and start the RPC server, so health checks and the un-gated (visibility) RPCs work while passive. Table loading moves to promotion. - `GetOrGenerateClusterId()` is restructured into three explicit branches; the new one is "no cluster ID yet **and** passive" → wait for the leader to write it (1s retry, rate-limited log) instead of minting one. - The GCS-pid and autoscaler-v2-flag `Put()`s are extracted into `WriteGcsPid()` / `WriteAutoscalerV2Flag()`, still called inline when leader election is off. - `RecordMetrics()` and the startup metrics-exporter init move into `StartMetricsReporting()`, now active-only: `RecordMetrics()` writes actor and placement-group usage counters to shared storage, and a passive GCS (empty tables) would overwrite the leader's counts with zeroes — a GCS-initiated write that RPC gating cannot catch. `PrintDebugState()` keeps running while passive so a standby is not dark. **2. Head-node handover — `gcs_node_manager.{h,cc}`** - `PromoteNodeManager()` replays the head node cached in `passive_local_node_` through the real `HandleRegisterNode` path, so it is persisted, publishes `NODE_ADDED`, and — because head registration marks every alive head dead — retires the stale head hydrated from storage. Without it the cluster reports two live heads after a failover. - `ClearPassiveLocalNode()` → `GetPassiveLocalNode()`: the cache is read, not taken, and released from the registration callback once `alive_nodes_` tracks the node. Taking it up front left the head in neither place while two chained storage writes completed (the stale head's DEAD record, then its own), so the un-gated visibility RPCs reported no live head mid-handover. The member is a `std::optional` — it is a value that may be absent, and nothing hands a pointer to it out past `mutex_`. - `CachePassiveLocalNode()` → `TryHandlePassiveHeadRegistration()`, returning whether the registration was handled. The gated handler used to reply `OK` unconditionally; if promotion landed between its `!is_leader_fn_()` check and the cache write, the node was neither cached nor registered, and the raylet never retries an `OK`. On`false` the handler now falls through to the real `HandleRegisterNode`. **3. `GcsServer::PromoteToLeader()`** - Loads the tables, `HydrateManagers()`, flips `is_leader_`, promotes the node manager, `WriteActiveOnlyKeys()`, `StartMetricsReporting()`. - Order is load-bearing: flipping `is_leader_` earlier serves mutating RPCs against half-loaded state; promoting the node manager earlier registers the local head before the stale one is loaded, leaving two live heads. - `HydrateManagers()` covers every manager, in `DoStart()`'s order, because `GcsNodeManager::Initialize()` no longer notifies the node-added listeners. Relying on that fan-out was wrong twice over: `Postable::Post` enqueues rather than runs inline, so `GcsPlacementGroupManager::Initialize()` scheduled its pending groups against a zero-node resource view, and the previous leader's head reached the listener's metrics branch and took the one-shot `metrics_exporter_initialized_` latch with a remote agent port. Suppressing the fan-out is a no-op for `DoStart()`, where the listener list is still empty at that point. - Guarded on `IsLeader() || promotion_started_` — neither alone is enough, and a second load would hydrate twice (`GcsJobManager` bumps a per-job reference count that would never drop back to zero). - Promotion arriving while `Start()` is parked on the cluster-ID wait just flips `is_leader_`: that wait only ends when a leader writes the ID, and that leader is now us. The continuation then boots active and runs `WriteActiveOnlyKeys()`. **4. Flag wiring — `gcs_server_main.cc`** - Assign `GcsServerConfig::enable_gcs_leader_election` from `RayConfig::ENABLE_GCS_LEADER_ELECTION()` (env `RAY_ENABLE_GCS_LEADER_ELECTION`). Nothing assigned it before, so the passive/promotion paths were unreachable. - Field renamed `ray_leader_elect_enabled` → `enable_gcs_leader_election` (internal struct field only) so the feature greps as one name. - Loud startup `WARNING`: no production caller drives promotion yet, so a lone head with the flag set parks on the cluster-ID wait. Better an explicit warning than something that looks like a hang. The warning goes away once the elector lands. ## Tests ### Unit — `//src/ray/gcs/tests:gcs_node_manager_test` Exercises `GcsNodeManager` in isolation (no server, no Redis), pinning the head-node cache semantics independently of how promotion is driven. | Test | What it guards | | :--- | :--- | | `TestPromoteRegistersCachedHeadAndKillsStaleHead` | The head cached while passive becomes a real alive node on promotion, the stale head is marked dead, and a second promotion registers nothing again. | | `TestPromoteIsNoopWithoutCachedHead` | The default (leader-election-off) path, where nothing was ever cached, must not invent a registration. | | `TestPassiveHeadRegistrationSkipsWhenPromoted` | Registration is async, so this covers the window after promotion but before `alive_nodes_` is populated. The head promotion is registering is reported handled; any other head is not, so the caller registers it instead of dropping it. | | `TestHeadStaysVisibleDuringPromotionHandover` | Mid-handover, with the stale head already retired and the storage write still in flight, CheckAlive and the alive-head query must already answer with the promoted head. | | `TestInitializeDoesNotNotifyNodeAddedListeners` | Initialize() restores the cache without emitting node-added events, which is what lets HydrateManagers() feed the downstream managers itself. | ### `//src/ray/gcs/tests:gcs_leader_gated_handlers_test` Extended `TestNodeRegistrationAndGating`: when the cache reports the registration was not handled, the proxy must fall through to the real handler instead of replying OK. | ### Integration — `//src/ray/gcs/tests:gcs_server_rpc_test` Real `GcsServer` processes against a real Redis over real gRPC. Two heads with leader election enabled is the only topology a production cluster produces, so `GcsLeaderElectionTestBase` starts no GCS of its own and `GcsLeaderElectionTest` adds one promoted leader. | Test | What it guards | | :--- | :--- | | `TestPassiveServerReadiness` | A passive GCS adopts the leader's cluster ID, serves health checks, and reports `is_leader=false` over `CheckAlive`. | | `TestColdStartPromotionBootsWinnerAndLoser` | A cluster coming up for the first time: two candidates park against empty storage writing nothing; promoting one releases its own cluster-ID wait instead of deadlocking, writes the three keys, and thereby unblocks the other, which adopts the same ID and stays passive. | | `TestPromotionActivatesTheServer` | Before promotion a passive GCS cannot see a node the leader persisted and rejects RegisterNode with GcsPassive; after promotion it serves that node from storage, reports its resources through GetAllTotalResources (the resource manager is hydrated, not just the node table), and accepts the same registration. | | `TestPromotionHandsOverTheHeadNode` | The head handover a failover comes down to: the cached local head reaches storage only at promotion, the head it replaces is retired, and exactly one head stays alive. | | `TestPromotionRewritesActiveOnlyKeys` | A promoted GCS updates the GCS pid and autoscaler-v2 flag rather than leaving the previous leader's values. | | `TestPromotionIsIdempotent` | The elector re-invokes `on_started_leading`; both calls are issued from one handler so the second also lands while the first is still loading tables. | ### Manual — the legacy path is untouched No unit test covers `main()`, and the point of this PR is that a normal cluster does not notice it, so the default path was exercised on a real cluster with the flag unset. Both entry points were checked because `ray.init()` and `ray start --head` reach `gcs_server_main.cc` differently. Via `ray.init()`: - the flag defaults to `False` and the env var is unset - tasks and actors run normally - one alive node, which is the driver's node; reading the GCS node table directly shows exactly one alive `is_head_node` - `gcs_pid` and `__autoscaler_v2_enabled` are both present in the KV store at startup, confirming the extracted writes still happen inline - `is_gcs_leader()` and `is_gcs_leader_local()` both return `True` - `gcs_server.out` contains no leader-election lines at all and logs normal cluster-ID generation - clean `ray.shutdown()` Via `ray start --head`: the cluster starts, `ray status` reports the node active with full resources, the GCS log again shows no leader-election lines, and `ray stop` leaves no stray processes. With the flag **on**, the same binary logs the experimental warning, starts passive, and parks on the cluster-ID wait without ever writing one, because the leader election lib has not been integrated yet. ## Related issues ray-project#63643 ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Yuchen Zhou <[email protected]>

Description
This PR introduces the support for the Ray Head Node by enabling a hot standby Active-Passive GCS server configuration when the environment variable RAY_LEADER_ELECT=true is set.
Behavior change
How the PR is tested
Besides the units tests, I added the integration tests
test_passive_head_e2e.pyto e2e integration test starting a real shared Redis instance, an active head A, and a passive head B. It validates the GCS readiness endpoints (200 for A, 503 for B), verifies that only active node A is registered in the Redis NodeTable, and checks that both node processes remain alive without crashing.Manual test
Key changes
GCS server end (C++)
GCS refactoring: gcs_server.cc
DoStartLoadingDeferred()to defer data loading and initialization to promotion. The function is not used yet.GetOrGenerateClusterId()if the gcs is passive which avoids the cluster id write conflict.Passive head node registration caching and promotion
GcsNodeManager::HandleRegisterNodeto handle passive node registrations:passive_local_node_without persisting it to the GCS storage.CheckAlive,GetAllNodeInfo, andIsNodeAliveto read the cached passive_local_node_ state so local components on the passive node function correctly.GcsNodeManager::PromoteNodeManager()to register the cached in-memory local node to GCS storage through the standard active pipeline upon GCS active leader promotion.GCS Protobuf & Health Status
Added the
is_leaderfield to the GCSCheckAliveReplyprotobuf message.Separated GCS liveness checking (is GCS process alive) from GCS active leadership (readiness) checking in the Dashboard health checker.
C++ GCS RPC Gating on leadership status, allowed RPCs
Client-side accessors and propogated cython bindings
Autoscaler) that do not have a periodic background heartbeat loop. They call this to fetch the most up-to-date leadership status from the network.Dashboard headorTelemetry report loop) that already have a periodic check-alive background loop running.New system config
Other head components (Python)
ValueError: GCS passiveand unblock the startupdashboard_url = ""to allow node startup loops to complete cleanly._gcs_check_alive()background check loop whenRAY_LEADER_ELECTis enabled to update local GCS client leadership cache. Defers registration of agent node addresses in GCS KV inside_register_agent()retry loop, pushing values to GCS only when local cache confirms GCS is the active leader.DashboardAddressandDashboardMetricsAddressto GCS internal KV during standby startup. Spins up a background task loop_register_addresses_loop()that polls the GCS leadership cache and registers the host:port values to GCS KV immediately upon promotion.is_gcs_leader()checks, ensuring no autoscaling operations or telemetry updates occur while the local GCS is passive.is_gcs_leader()returns false.Related issues
#63643
Additional information