Skip to content

[core][gcs][Actice-Passive] Phase 2.3 Passive head lifecycle change - #66222

Merged
rueian merged 8 commits into
ray-project:masterfrom
YoyinZyc:passive_gcs_promotion
Sep 24, 2026
Merged

rueian merged 8 commits into
ray-project:masterfrom
YoyinZyc:passive_gcs_promotion

Conversation

@YoyinZyc

@YoyinZyc YoyinZyc commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

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.

image

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

@YoyinZyc
YoyinZyc requested a review from a team as a code owner September 17, 2026 01:06

@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 the active-passive GCS leader election promotion path, deferring table loading and shared-storage writes until a GCS instance is promoted to leader. It introduces PromoteToLeader in GcsServer to handle manager hydration and node manager promotion, and updates GcsNodeManager to cache and register the local head node upon promotion. Feedback on these changes highlights a potential data race in PromoteToLeader if called from external threads, suggesting that the method's body be posted to the default IO context. Additionally, a potential use-after-free vulnerability was identified in the cluster ID retry timer callback within GetOrGenerateClusterId if the server is destroyed while the timer is pending.

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

Stale Bugbot comment from a previous run.

Comment thread src/ray/gcs/gcs_node_manager.h Resolved
@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Sep 17, 2026
@YoyinZyc

Copy link
Copy Markdown
Contributor Author

This is one of the most refactor pr of active-passive implementation.
@rueian @ryanaoleary @jhasm Please take a look if you have time. Thanks!

@jhasm jhasm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

👍 LGTM

Comment thread src/ray/gcs/gcs_server.cc Resolved
Comment thread src/ray/gcs/gcs_server.cc Resolved
Make startup safe for a standby head that shares storage with an active leader.
All of it sits behind GcsServerConfig::ray_leader_elect_enabled, which nothing
assigns yet, so the default path is unchanged.

A passive boot skips the table load and every shared-storage write, resolving
only the cluster ID before starting the RPC server so health checks and the
allowed RPCs still work; table loading moves to promotion. A passive GCS waits
for the leader's cluster ID rather than minting one. The GCS-pid and
autoscaler-v2-flag writes move into WriteGcsPid() and WriteAutoscalerV2Flag(),
still inline when leader election is off.

Metrics are deliberately left on: a standby tags them with its own NodeAddress,
so it stays observable rather than dark until promoted.

Tests (gcs_server_rpc_test):
- TestPassiveServerReadiness: adopts the leader's cluster ID, serves health
  checks, reports is_leader=false.
- TestPassiveWaitsForClusterIdAndNeverWritesIt: stays unstarted while storage
  has no ID, proving it wrote none, and starts once a leader writes one.

Signed-off-by: Yuchen Zhou <[email protected]>
@YoyinZyc
YoyinZyc force-pushed the passive_gcs_promotion branch from d2b8c19 to ed3d226 Compare September 21, 2026 18:10

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Fix All in Cursor

Reviewed by Cursor Bugbot for commit ed3d226. Configure here.

Comment thread src/ray/gcs/gcs_node_manager.cc Resolved
@ryanaoleary

Copy link
Copy Markdown
Contributor

change LGTM, one last comment from cursor I think is valid and then will approve

@ryanaoleary

Copy link
Copy Markdown
Contributor

cc: @edoakes @rueian needs a Ray core reviewer

While passive, the leader-gated NodeInfo handler stashes the local head node's
registration in GcsNodeManager's passive_local_node_ cache instead of persisting
it. Nothing consumed that cache, so a promoted GCS would serve a head node that
exists only in its own memory.

PromoteNodeManager() replays the cached head through the normal
HandleRegisterNode path. Going through the real handler is what makes the entry
persist, publish NODE_ADDED, and -- because head registration marks every alive
head dead -- retire the stale head hydrated from storage; otherwise the cluster
reports two live heads after a failover.

The cache is read rather than taken, and released from the registration
callback. Registration retires the stale head from alive_nodes_ synchronously,
but the promoted head only lands there after two chained storage writes: the
stale head's DEAD record, then its own. Taking the cache up front would leave
the head in neither place for that whole window, so CheckAlive, GetAllNodeInfo
and GetAllNodeAddressAndLiveness -- un-gated, and already answering for a GCS
that has set is_leader_ -- would report no live head, and a head that was
visible before promotion and after it would appear to vanish in between. The
callback runs from HandleRegisterNode's completion handler, which still holds
mutex_ and has already populated alive_nodes_, so the handover is one critical
section. Readers skip the cache once alive_nodes_/dead_nodes_ knows the id, so
it is never double-counted while both hold it.

No production caller yet; the GcsServer side that hydrates and then calls this
is the next commit, and the header documents that ordering as a precondition.

Tests (gcs_node_manager_test), under GcsNodeManagerPromotionTest whose AllNodes()
helper also asserts no node id is reported twice:
- TestPromoteRegistersCachedHeadAndKillsStaleHead: the cached head becomes alive,
  the hydrated stale head is marked dead, and a second promotion registers
  nothing again.
- TestPromoteIsNoopWithoutCachedHead: the default path, where nothing was cached,
  must not invent a registration.
- TestCachePassiveLocalNodeSkipsWhenPromoted: registration is async, so this
  covers the window after promotion but before alive_nodes_ is populated, where
  only the leadership check can reject a late call.
- TestHeadStaysVisibleDuringPromotionHandover: mid-handover, with the stale head
  already retired and the storage write still in flight, the promoted head must
  already answer CheckAlive and the alive-head query.

Signed-off-by: Yuchen Zhou <[email protected]>
A passive GCS never loaded the GCS tables and skipped the shared-storage writes,
so nothing yet turns one into a working leader. PromoteToLeader() loads those
tables, hydrates the managers, opens the RPC gate, registers the head node cached
while passive, and performs the deferred writes.

Order matters: hydrate, then flip is_leader_, then promote the node manager.
Flipping earlier serves mutating RPCs against half-loaded state; promoting
earlier registers the local head before the stale one is loaded, leaving the
cluster reporting two live heads.

HydrateManagers() covers fewer managers than DoStart. By promotion time the
node-added listeners are installed, so loading the node table already fans every
alive node out to the resource, placement group, autoscaler and health check
managers; hydrating those again applies each node twice, which
GcsHealthCheckManager::AddNode RAY_CHECKs against.

Promotion is guarded on IsLeader() || promotion_started_. Neither alone is
enough: is_leader_ only flips once the load completes, so a call in that window
would start a second load, while promotion_started_ misses a GCS already active
without having run this path. A second load hydrates twice, and 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 flips
is_leader_ rather than returning: that wait only ends when a leader writes the
ID, and that leader is now us. The continuation then boots active and must run
WriteActiveOnlyKeys() too, since the init-time writes are skipped whenever leader
election is enabled.

RecordMetrics moves into StartMetricsReporting(), shared with promotion, because
it writes usage counters to shared storage and a passive GCS would overwrite the
leader's counts with zeroes -- a GCS-initiated write the RPC gating cannot catch.
PrintDebugState keeps running while passive so a standby is not dark.

No production caller yet; the elector's on_started_leading will drive it, on the
single-threaded default io context so it cannot interleave with Start().

Tests (gcs_server_rpc_test), against the only topology a real cluster produces:
GcsLeaderElectionTestBase starts no GCS, GcsLeaderElectionTest adds one promoted
leader, promotion is posted onto the server's own io context the way the elector
will, and assertions that must distinguish persisted state from an in-process
cache read Redis directly.
- TestColdStartPromotionBootsWinnerAndLoser: two candidates park against empty
  storage writing nothing; promoting one releases its own cluster-ID wait, writes
  the three keys, and unblocks the other, which stays passive on the same ID.
- TestPromotionActivatesTheServer: GcsPassive and an empty node table before,
  serving the persisted node and accepting registrations after.
- TestPromotionHandsOverTheHeadNode: the cached local head reaches storage only
  at promotion, the head it replaces is retired, and exactly one head stays
  alive, which is what pins the hydrate-then-register order.
- TestPromotionRewritesActiveOnlyKeys: claims the GCS pid and autoscaler-v2 flag
  instead of leaving the previous leader's values.
- TestPromotionIsIdempotent: both calls issue from one handler, so the second
  lands while the first is still loading tables.

Signed-off-by: Yuchen Zhou <[email protected]>
The passive and promotion paths were unreachable: nothing assigned
GcsServerConfig::enable_gcs_leader_election, so every GCS booted active. Read it
from RayConfig, which picks up the RAY_ENABLE_GCS_LEADER_ELECTION env var. The
default is still false, so a normal cluster is unaffected.

Rename the field from ray_leader_elect_enabled while wiring it up. It was named
after RAY_LEADER_ELECT, the env var this feature used before review renamed it,
so the whole feature now greps as one name and matches the struct's other
enable_* fields.

Enabling it is not yet useful: nothing drives promotion, so the GCS stays passive
and a lone head blocks in startup waiting for a cluster ID nobody writes. Warn at
startup rather than let that look like a hang; the warning goes once the elector
is wired up.

No unit test covers main(), so this was verified against the built binary: the
default run is unchanged, and with the env var set the GCS logs the warning,
starts passive, and parks on the cluster-ID wait without ever writing one.

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

GcsNodeManager::Initialize() notified the node-added listeners for every node
it restored. In DoStart that is a no-op: InstallEventListeners() runs after it,
so the listener list is still empty, and each manager is hydrated by its own
InitXxx(). On the promotion path the listeners are already installed, so the
node table load drove them instead -- and Postable::Post() enqueues rather than
runs inline, so they only drained after promotion had already finished. Two
consequences:

- GcsPlacementGroupManager::Initialize() ends in
  SchedulePendingPlacementGroups() and ran while gcs_resource_manager_ still
  had no nodes, so every persisted placement group went straight to INFEASIBLE
  and was only rescheduled once the queued events drained.

- The previous leader's head node, loaded from storage, reached the listener's
  metrics branch and took the one-shot metrics_exporter_initialized_ latch with
  its own agent port. InitMetricsExporter() pairs that port with
  GetLocalhostIP(), the latch never resets, and a failed WaitForServerReady() is
  not retried, so the local head's port was ignored for the life of the process.

Initialize() no longer notifies, and HydrateManagers() hydrates every manager
explicitly in the order DoStart uses. The health check hydration loop moves out
of InitGcsHealthCheckManager() so both paths share it. DoStart is unchanged: its
listener list is empty at that point, so the suppressed notifications never
happened there to begin with.

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

LeaderGatedNodeInfoHandler::HandleRegisterNode checks is_leader_fn_() on the
node manager's io context, then caches the head node, then replies OK
unconditionally. The cache re-checks leadership under mutex_, and if promotion
landed on the default io context in between it returned without caching. The
raylet still got OK, treats the node as registered and never retries, so a head
that nothing else registers is lost: no entry in the node table, no health
check, and nothing in ray.nodes().

CachePassiveLocalNode becomes TryHandlePassiveHeadRegistration and reports
whether the registration was handled. "Cache" did not match the return value:
two of the three true cases do not cache anything. Handling does -- the node is
handled when it is freshly cached, when alive_nodes_/dead_nodes_ already tracks
it, and when it is the head the in-flight promotion is registering. It is
unhandled only when this GCS is the leader and the promotion is registering a
different head, and the handler then falls through to the real
HandleRegisterNode instead of acknowledging it.

The alive/dead check moves ahead of the leadership check, since a node already
in the table is handled no matter who is leader. Returning false there would
send an already-registered head back through registration, which retires it as
a stale head and broadcasts it DEAD.

Signed-off-by: Yuchen Zhou <[email protected]>
@YoyinZyc
YoyinZyc force-pushed the passive_gcs_promotion branch from 8acdd9a to 7c61169 Compare September 22, 2026 18:36
@rueian rueian added the go add ONLY when ready to merge, run all tests label Sep 22, 2026
@rueian
rueian merged commit d758095 into ray-project:master Sep 24, 2026
7 checks passed
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 go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants