Skip to content

[Active-Passive] Phase 2: GCS and other head components refactor for Passive Mode - #64422

Closed
YoyinZyc wants to merge 15 commits into
ray-project:masterfrom
YoyinZyc:gcs_standby_mode
Closed

YoyinZyc wants to merge 15 commits into
ray-project:masterfrom
YoyinZyc:gcs_standby_mode

Conversation

@YoyinZyc

Copy link
Copy Markdown
Contributor

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

  1. Run gcs server in passive mode
    • Restrict rpc requests and only allow the necessary rpcs
    • Defer table initialization to promotion
    • Caches the local head node registration (from the local Raylet) only in-memory inside passive_local_node_ without writing it to Redis. It reports this head node as ALIVE locally, enabling local processes to start up cleanly without corrupting shared Redis storage.
  2. Introduce readiness probe which checks the GCS leadership status
  3. Suppress other components on Ray head if needed
  4. Promotion logic is out of scope of this PR.
  5. Single-head ray cluster lifecycle remains unchanged

How the PR is tested

Besides the units tests, I added the integration tests test_passive_head_e2e.py to 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

  1. Spins up a shared Redis instance on port 6379.
  2. Starts Node A (Active Head: GCS 6380, Dashboard 8265) with RAY_LEADER_ELECT=false.
  3. Starts Node B (Standby Head: GCS 6381, Dashboard 8266) with RAY_LEADER_ELECT=true.
  4. Verify port health probes:
    • Expect Node A's /api/gcs_readiness and /api/healthz?readiness=true to return status 200 OK.
    • Expect Node B's /api/gcs_readiness and /api/healthz?readiness=true to fail with status 503 Service Unavailable.
  5. Submit a job to Node A: passed
  6. Submit a job to Node B: rejected

Key changes

GCS server end (C++)

  1. GCS refactoring: gcs_server.cc

    • Added DoStartLoadingDeferred() to defer data loading and initialization to promotion. The function is not used yet.
    • Async fetch cluster id in GetOrGenerateClusterId() if the gcs is passive which avoids the cluster id write conflict.
  2. Passive head node registration caching and promotion

    • Refactored GcsNodeManager::HandleRegisterNode to handle passive node registrations:
      • Rejects registration requests from worker nodes on standby GCS servers.
      • Allows local head node registration (from local Raylet) on the standby GCS, caching it in-memory inside passive_local_node_ without persisting it to the GCS storage.
    • Updated CheckAlive, GetAllNodeInfo, and IsNodeAlive to read the cached passive_local_node_ state so local components on the passive node function correctly.
    • Added GcsNodeManager::PromoteNodeManager() to register the cached in-memory local node to GCS storage through the standard active pipeline upon GCS active leader promotion.
  3. GCS Protobuf & Health Status

    • Added the is_leader field to the GCS CheckAliveReply protobuf message.

    • Separated GCS liveness checking (is GCS process alive) from GCS active leadership (readiness) checking in the Dashboard health checker.

      Probe type HTTP endpoint Active Passive
      GCS Liveness /api/gcs_healthz 200 OK 200 OK
      GCS Readiness(NEW) /api/gcs_readiness 200 OK 503 Service Unavailable
      Dashboard Unified Liveness /api/healthz 200 OK 200 OK
      Dashboard Unified Readiness(NEW) /api/gcs_readiness?readiness=true 200 OK 503 Service Unavailable
  4. C++ GCS RPC Gating on leadership status, allowed RPCs

    • NodeInfoGcsService:
      • GetClusterId (Allows clients to read the cluster ID).
      • CheckAlive (Allows clients/agents to check node status).
      • GetAllNodeInfo & GetAllNodeAddressAndLiveness (Allows log monitors and components to discover active nodes).
      • RegisterNode (Allowed ONLY if the registering node is the local head node itself). All other worker node registrations are blocked.
    • InternalKVGcsService
      • GetInternalConfig (Allows components to read system configs).
      • InternalKVGet (Allows components to read configs)
  5. Client-side accessors and propogated cython bindings

    • IsGcsLeader(): it triggers a direct CheckAlive RPC network query to the GCS server, waits for the response, updates the local C++ cache, and then returns the updated status. Used by components (like the 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.
    • IsGcsLeaderLocal(): it returns the cached leadership status currently stored in-memory in C++ without any network call. Used by background components (like the Dashboard head or Telemetry report loop) that already have a periodic check-alive background loop running.
  6. New system config

    • LEADER_ELECT (bool, default false): Enables the C++ GCS leader election gating logic inside the GCS daemon.

Other head components (Python)

  1. node.py (Head node initialization)
    • Added error handling around cluster metadata, session name, and tracing hook initializations. Catch status ValueError: GCS passive and unblock the startup
  2. services.py (Dashboard process startup)
    • Reads configuration to identify if GCS is running in passive standby mode. If passive, it skips blocking on polling the GCS internal KV for dashboard addresses. Instead, it checks if the subprocess remains alive for 2 seconds and defaults dashboard_url = "" to allow node startup loops to complete cleanly.
  3. agent.py (Dashboard agent)
    • Implements _gcs_check_alive() background check loop when RAY_LEADER_ELECT is 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.
  4. head.py (Dashboard head)
    • Defers writing DashboardAddress and DashboardMetricsAddress to 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.
  5. monitor.py (Autoscaler)
    • Wraps the main execution thread inside is_gcs_leader() checks, ensuring no autoscaling operations or telemetry updates occur while the local GCS is passive.
  6. log_monitor.py (Log Forwarding)
    • Suppress log forwarding if is_gcs_leader() returns false.
  7. usage_stats_head.py (Telemetry)
    • Suppress stats submission on passive head

Related issues

#63643

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

@YoyinZyc
YoyinZyc marked this pull request as draft June 29, 2026 20:13
Comment thread src/ray/gcs/gcs_node_manager.cc Resolved

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

Comment thread python/ray/_private/services.py Resolved
Comment thread python/ray/dashboard/agent.py Resolved
Comment thread python/ray/dashboard/agent.py Resolved
Comment thread python/ray/_private/log_monitor.py Resolved
@YoyinZyc
YoyinZyc marked this pull request as ready for review June 29, 2026 22:20
@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Jun 30, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

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.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Jul 14, 2026
Comment thread src/ray/gcs/gcs_server.h
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_;

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.

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?

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.

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.

@rueian rueian Jul 27, 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.

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_)
}

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.

BTW, is RaySyncerService intentionally not gated?

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Jul 18, 2026
YoyinZyc added 12 commits July 22, 2026 22:51
…centralized leader-gated service proxies

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]>
…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]>
…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]>
Comment thread src/ray/gcs/gcs_server.cc Resolved

@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 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit b656e40. Configure here.

Comment thread python/ray/_private/node.py Resolved
Comment thread src/ray/gcs/gcs_server.h Resolved
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:

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.

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():

@ryanaoleary ryanaoleary Jul 28, 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.

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()

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.

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

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 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

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.

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):

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.

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()

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.

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

@ryanaoleary

Copy link
Copy Markdown
Contributor

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.

@YoyinZyc

Copy link
Copy Markdown
Contributor Author

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.

edoakes pushed a commit that referenced this pull request Aug 12, 2026
…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]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…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]>
@rueian

rueian commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Since this PR is going to be split into small parts, let's close it.

@rueian rueian closed this Aug 21, 2026
rueian added a commit that referenced this pull request Sep 15, 2026
…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]>
rueian pushed a commit that referenced this pull request Sep 24, 2026
…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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…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]>
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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…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]>
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 unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants