Skip to content

[Active-Passive] Phase 2.4 Adjust the components on head node to be compatible with passive setup - #66635

Merged
edoakes merged 12 commits into
ray-project:masterfrom
YoyinZyc:passive_python_head
Nov 4, 2026
Merged

edoakes merged 12 commits into
ray-project:masterfrom
YoyinZyc:passive_python_head

Conversation

@YoyinZyc

@YoyinZyc YoyinZyc commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

Under the Active-Passive GCS architecture (RAY_ENABLE_GCS_LEADER_ELECTION=true), a passive GCS instance rejects all mutating RPCs with StatusCode::GcsPassive. Previously, Python head processes (ray start --head, Dashboard, Autoscaler, Log Monitor, Reporter) assumed they were always talking to an active GCS. Consequently, starting a passive head led to fatal crashes, 60-second startup hangs, log-bombing, or state divergence upon failover.

This PR makes all Python head components resilient to passive GCS write refusals. Passive heads can now boot cleanly, idle safely without split-brain side effects, suppress repetitive error logging, and seamlessly replay critical cluster state upon promotion to leader.

All changes are gated behind RAY_ENABLE_GCS_LEADER_ELECTION (default False), ensuring zero behavioral impact when leader election is disabled.

Key Changes (by Subsystem)

1. Core Exception & Centralized Passive Utilities

  • Dedicated Exception (GcsPassiveError): Subclasses RpcError to distinguish expected passive GCS write refusals from fatal network partitions or GCS crashes without relying on fragile error string parsing.
  • Consolidated Utilities (ray._private.gcs_passive_utils):
    • is_refused_by_passive_gcs(exc, latch=None): Unified predicate for passive refusal detection.
    • PassiveLatch: Edge-triggered latch that logs transitions entering and exiting passive mode once, eliminating per-second log spam across loops.
    • wait_until_gcs_leader(): Async loop gating utility that suspends processing until the node is promoted.
    • Passive-safe KV helpers (put_kv_passive_safe, async_put_kv_passive_safe, del_kv_passive_safe, async_del_kv_passive_safe): Unified sync/async helpers handling passive refusals and latch transitions cleanly.

2. Head Node Bootstrap & Process Supervision (ray start --head)

  • Survive Passive Write Rejections: _write_cluster_info_to_kv() catches GcsPassiveError and allows node initialization to continue without writing initial cluster info.
  • Eliminate 60s Startup Timeout: start_api_server() skips polling for DASHBOARD_ADDRESS when GCS is passive and returns process_info immediately. This prevents a 60-second stall and avoids dropping the dashboard from KubeRay’s dead_processes() liveness supervisor.
  • Skip Dead Writes: Passive nodes skip writing webui:url to GCS since the URL is deferred until promotion.

3. Dashboard Head, Agents & Promotion Replay Contract

  • Dashboard Agent Survival: Dashboard Agent retries registering its node-specific address rather than crashing on passive refusal (preventing the fate-shared Raylet on the passive head from dying).
  • Dashboard Head Promotion Loop: Dashboard Head defers publishing its address and waits for leadership in _register_addresses_loop() (leveraging existing _gcs_check_alive() cache without extra RPCs).
  • Explicit Promotion Replay Contract (HEAD_PROMOTION_REPLAY_KEYS): Defined in dashboard/consts.py to enumerate all keys that must be replayed upon promotion (DASHBOARD_ADDRESS, webui:url, session_name, CLUSTER_METADATA, tracing_startup_hook, and bulk extra usage tags).
  • Agent Log Muting: EventAgent and ReporterAgent use PassiveLatch to mute repetitive registration failures while waiting for promotion.

4. NodeHead Subprocess

  • Pause Subscriptions on Passive: Uses wait_until_gcs_leader() to pause node and actor update subscriptions until promoted.
  • State Consistency: Records _registered_head_node_id only after the KV put succeeds to prevent poisoned in-memory state on write rejections.
  • Passive-Safe Address Cleanup: Dead node agent address cleanup (_delete_agent_addresses) ignores passive GCS refusals.
  • Fault Isolation: Catches per-node update errors in _update_nodes so a single malformed entry does not terminate the subscription loop.

5. Autoscaler Monitors (v1 & v2)

  • Pause autoscaler on Passive
  • Safe Startup: Catches passive rejections during AutoscalerMetricsAddress registration and DEBUG_AUTOSCALING_ERROR cleanup.
  • Split-Brain Prevention: Reconcile loops in both v1 and v2 check is_gcs_leader() before each pass, remaining idle while passive. This prevents passive heads from issuing unauthorized node launches or terminations to cloud providers.
  • Promotion Takeover: On promotion, atomically rewrites AutoscalerMetricsAddress and clears stale error status so ray status reflects the newly active autoscaler.

6. Log Monitor

  • Log-Storm Suppression: Catches GcsPassiveError on rejected log publish batches and uses PassiveLatch to log state transitions once.
  • Continuous File Consumption: Continues advancing file read offsets while passive instead of parking. This avoids costly is_gcs_leader() polling and prevents massive re-reading/publishing log storms upon promotion.

7. Usage Stats & Telemetry

  • Silence Passive Telemetry: Restricts UsageStatsHead reporting to active leaders, preventing duplicate empty telemetry reports under the same session ID.
  • Graceful Metadata Read: get_cluster_metadata() returns None instead of raising AttributeError when the key has not yet been written, allowing early joining workers to connect safely.

###GCS internal_kv Key Handling Strategies

Because different cluster state keys have distinct consistency requirements and lifecycles, mutating operations on GCS internal_kv are categorized into explicit synchronization strategies:

Key Namespace Strategy Passive Startup Behavior Promotion Behavior Design Rationale & Considerations
session_name KV_NAMESPACE_SESSION
("session")
Write When Absent
(overwrite=False)
Node._write_cluster_info_to_kv() catches write refusal and skips; startup continues. Replayed by DashboardHead with overwrite=False. Idempotent recovery: Cluster must have exactly one immutable session name. If the previous leader already wrote it, promotion will not overwrite it; if the previous leader crashed before writing it, this closes the gap so workers can join.
CLUSTER_METADATA KV_NAMESPACE_CLUSTER
("cluster")
Deferred Overwrite
(overwrite=True)
Node catches write refusal and skips. Readers return None instead of raising AttributeError. Replayed by DashboardHead with overwrite=True; ReporterHead stops permanently caching it. Supports rolling upgrades: Passive head may be upgraded before taking over. Overwriting ensures joining workers validate version compatibility against the promoted head rather than a decommissioned predecessor.
DASHBOARD_ADDRESS KV_NAMESPACE_DASHBOARD
("dashboard")
Deferred to Promotion
(overwrite=True)
DashboardHead defers registration; start_api_server() skips polling and returns process_info immediately. Replayed by DashboardHead with overwrite=True. Eliminates 60s hang & preserves supervision: Avoids burning RAY_DASHBOARD_STARTUP_TIMEOUT_S. Returning valid process_info prevents KubeRay's dead_processes() monitor from losing track of the spawned dashboard.
webui:url KV_NAMESPACE_DASHBOARD
("dashboard")
Skip & Deferred
(overwrite=True)
Node skips writing webui:url upon detecting a passive GCS. Replayed by DashboardHead with overwrite=True. Avoids deterministic write failure: Uses the explicit passive rejection signal from the preceding write rather than relying on delayed leadership caches.
DashboardMetricsAddress None (default) Deferred to Promotion
(overwrite=True)
DashboardHead catches write refusal and suppresses registration. Replayed by DashboardHead with overwrite=True. Metrics routing: Ensures metrics collectors (e.g. Prometheus) only scrape the currently active dashboard instance.
tracing_startup_hook KV_NAMESPACE_TRACING
("tracing")
Deferred to Promotion
(overwrite=True)
Node skips initial registration if GCS is passive. Replayed by DashboardHead with overwrite=True (if configured on startup). Distributed tracing continuity: Drivers read this key to determine whether to enable tracing; must be republished by the promoted head.
extra_usage_tag_*
(e.g. AUTOSCALER_VERSION)
KV_NAMESPACE_USAGE_STATS
("usage_stats")
In-Memory Buffering & Bulk Replay Buffered in in-memory dictionary; individual GCS write failures log at debug level and degrade silently. async_put_recorded_extra_usage_tags() bulk replays all buffered tags upon promotion. Telemetry completeness: Overcomes process-level memoization where tags recorded during passive would otherwise be marked "already recorded" and never re-sent.
AutoscalerMetricsAddress None (default) Deferred to Promotion
(overwrite=True)
Monitor startup catches rejection; PassiveLatch mutes repeat logs. Replayed once on promotion rising edge with overwrite=True. Endpoints consistency: Ensures ray status and monitoring tools query the active autoscaler rather than the dead predecessor.
DEBUG_AUTOSCALING_ERROR None (default) Deferred Cleanup / Safe Overwrite Startup deletion skips on passive; failure handler uses passive-safe write. Deleted in _resume_after_promotion() upon taking over. Prevents false death alerts: Avoids falsely reporting the autoscaler as dead during passive; clears stale errors left by the dead leader upon promotion.
DEBUG_AUTOSCALING_STATUS None (default) Leader-Only Loop Loop checks is_gcs_leader() before each pass; completely idles while passive. Reconcile loop activates and publishes periodic resource metrics. Split-brain prevention: Autoscaler mutates cloud provider resources (outside GCS gating); loop must never execute while in passive.
DASHBOARD_AGENT_ADDR_NODE_ID_PREFIX*
DASHBOARD_AGENT_ADDR_IP_PREFIX*
KV_NAMESPACE_DASHBOARD
("dashboard")
Retry In-Place Until OK
(Node-scoped, no replay)
DashboardAgent catches refusal and retries registration in background until accepted. No replay needed (key describes this specific node, not cluster leadership). Prevents node crash: Dashboard Agent is fate-shared with Raylet. Agent must survive write refusals on passive nodes without taking down the host.
Dead node agent addresses KV_NAMESPACE_DASHBOARD
("dashboard")
Tolerant Deletion
(Refusal safely ignored)
NodeHead calls async_internal_kv_del; passive refusals are caught and ignored. No replay needed (active leader already performed cleanup; rejoining agent will overwrite). Stateless passive: Avoids maintaining a dead-node cleanup queue across promotion.
head_node_id KV_NAMESPACE_JOB
("job")
Commit-After-Write
(overwrite=True)
Written by NodeHead when head node becomes ALIVE. Maintained by current active head. Memory state hygiene: In-memory _registered_head_node_id is only committed after the KV put succeeds, preventing poisoned state on write failure.

Test Plan

1. Layered Unit Test Suite

Covers isolated passive rejection handling, latches, loop gating, KV helpers, and promotion replay across all modified components.

####2. Manual test: Single-head cluster (Zero Regression)
Tested standard single-head cluster behavior with default settings (RAY_ENABLE_GCS_LEADER_ELECTION off):

  1. Cluster Startup and verify clean startup and all components are healthy.
  2. Submit a job and verify success.
  3. Logs are clean and no passive warning.

####3. Manual test: Standby Behavior Verification
Started a dual-head local cluster with Node A as active leader and Node B as passive standby

  1. Verify both head nodes remained alive
  2. Verify the components behavior on passive head
  3. Verify no log spamming

Related issues

#63643

@YoyinZyc YoyinZyc closed this Oct 1, 2026
@YoyinZyc YoyinZyc reopened this Oct 1, 2026
@YoyinZyc
YoyinZyc marked this pull request as draft October 1, 2026 19:03

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces comprehensive support for handling a passive (read-only) GCS state across various Ray components, including the autoscaler, dashboard, log monitor, and node management. It introduces a PassiveLatch utility to track GCS leadership and manage retries, along with a GcsPassiveError to specifically identify passive mode rejections. The reviewer provided actionable feedback to improve error handling in asyncio.gather, optimize sequential await calls using short-circuiting logic, and add defensive checks to exception handlers to prevent potential runtime errors.

Comment thread python/ray/dashboard/agent.py Resolved
Comment thread python/ray/dashboard/head.py 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 python/ray/dashboard/head.py Resolved
Comment thread python/ray/_common/usage/usage_lib.py Resolved
@YoyinZyc
YoyinZyc marked this pull request as ready for review October 1, 2026 21:08
@YoyinZyc YoyinZyc changed the title [Active-Passive] Phase 2.4 Adjust Head Python 1Services & Resilient Promotion [Active-Passive] Phase 2.4 Adjust the components on head node to be compatible with passive setup Oct 1, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces robust handling for passive GCS (Global Control Store) states during leader election in Ray, preventing components like the autoscaler, dashboard, and log monitor from crashing when GCS is in read-only standby mode. It adds utilities to safely defer and retry KV writes and registrations until a GCS promotion occurs. Feedback on the changes suggests using inspect.isawaitable instead of asyncio.iscoroutine to more reliably await aliveness checks, and optimizing the replay of recorded extra usage tags by executing the asynchronous writes concurrently with asyncio.gather.

Comment thread python/ray/_common/usage/usage_lib.py Resolved
@YoyinZyc
YoyinZyc force-pushed the passive_python_head branch from 7b05608 to ebc7cee Compare October 1, 2026 22:07

@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 python/ray/_private/node.py Resolved
@YoyinZyc
YoyinZyc force-pushed the passive_python_head branch from ebc7cee to 19108ef Compare October 1, 2026 22:34

@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 python/ray/dashboard/head.py Resolved
@YoyinZyc

YoyinZyc commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

@ryanaoleary @rueian @jhasm This PR is for the subprocesses running on the head node. Please take a look if you have time. Thanks!

@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Oct 2, 2026

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

Code Review Summary

The full current HEAD review found three issues in passive-head promotion and leadership probing. Inline-comment and REST-review retrieval was blocked, limiting prior-comment deduplication.

Files reviewed: 32
Issues found: 3

[logic_error] Promotion can advertise a disabled dashboard endpoint and permanently lose autoscaler takeover writes after a transient failure. [guideline_violation] The async leadership probe silently hides unexpected exceptions.

Comment thread python/ray/dashboard/head.py Resolved
The metrics address names the current leader's endpoint, so every promotion
rewrites it. Both writes get one attempt, as they do at startup.
"""
if not self._autoscaler_passive_latch.promoted():

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.

_resume_after_promotion calls latch.promoted(), which clears the promotion latch, before _publish_metrics_address and _clear_previous_autoscaling_error run. put_kv_passive_safe and del_kv_passive_safe re-raise any error that is not a passive-GCS refusal, such as a transient RpcError during failover. _run catches that error and retries, but promoted() now returns False, so neither write is attempted again while this head stays leader. AutoscalerMetricsAddress can keep pointing at the previous head, and a stale DEBUG_AUTOSCALING_ERROR can remain. The v2 AutoscalerMonitor._resume_after_promotion has the same ordering. Keep the takeover pending until the required writes succeed.

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.

The existing setup behavior of autoscaler is failing fast on _publish_metrics_address or _clear_previous_autoscaling_error exceptions.

So merely changing it to wait on success then clear latch could potentially cause a bad autoscaler(maybe caused by network partition) running forever. Instead, I moved the leadership check and _resume_after_promotion() outside _run()'s try...except Exception block so non-passive failures (e.g., RpcError from a network partition) fail fast and exit the monitor process for K8s to restart, matching startup behavior and DashboardHead.

logger.exception(e)
logger.info(f"Usage report failed: {e}")

def _is_passive_gcs(self) -> bool:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

From AI review:

UsageStatsHead._is_passive_gcs() races the initial CheckAlive RPC on active heads and permanently drops disabled-usage reports
Location: python/ray/dashboard/modules/usage_stats/usage_stats_head.py (_is_passive_gcs, _report_disabled_usage_async, run) and python/ray/dashboard/head.py (run)

  • Root cause:
    1. In C++ (NodeInfoAccessor::NodeInfoAccessor in src/ray/gcs_rpc_client/accessor.cc), is_gcs_leader_ is initialized to !RayConfig::instance().ENABLE_GCS_LEADER_ELECTION() — i.e., false when RAY_ENABLE_GCS_LEADER_ELECTION=1. It is only updated once a CheckAlive RPC response arrives (AsyncCheckAlive callback).
    2. In DashboardHead.run(), self.gcs_client = GcsClient(...) is instantiated and no CheckAlive call is made before starting concurrent_tasks:
      concurrent_tasks = [
          self._gcs_check_alive(),
          self._register_addresses_loop(),
      ]
      for m in dashboard_head_modules:
          concurrent_tasks.append(m.run())
      await asyncio.gather(*concurrent_tasks)
    3. On the first event-loop turn:
      • self._gcs_check_alive() calls await self.gcs_client.async_check_alive(node_ids=[], timeout=None) and yields control while the gRPC call is in flight.
      • UsageStatsHead.run() immediately runs in the same event-loop turn. When self.usage_stats_enabled is False, it does not sleep and immediately calls await self._report_disabled_usage_async().
      • _report_disabled_usage_async() synchronously calls self._is_passive_gcs(), which reads self.gcs_client.is_gcs_leader_local() before the in-flight async_check_alive() RPC can complete.
  • Impact:
    • Even on an active leader head node, when RAY_ENABLE_GCS_LEADER_ELECTION=1 and usage_stats_enabled=False, self.gcs_client.is_gcs_leader_local() is guaranteed to read the unprimed False cache value.
    • _is_passive_gcs() returns True, logs a false warning ("GCS is in passive mode. Skipping the usage report until promoted."), and UsageStatsHead.run() immediately returns — permanently skipping the disabled-usage report.
    • Furthermore, on a genuinely passive head that is later promoted, because UsageStatsHead.run() exits immediately after await self._report_disabled_usage_async(), the disabled-usage report is never sent after promotion either (and if RAY_USAGE_STATS_REPORT_INTERVAL_S is set small in tests, the first enabled usage report can similarly race the initial CheckAlive).
  • Suggested fix:
    • Either prime await self.gcs_client.async_check_alive(node_ids=[], timeout=...) once in DashboardHead.run() before starting dashboard_head_modules, and/or have _report_disabled_usage_async() wait via await wait_until_gcs_leader(self.gcs_client, latch=self._usage_passive_latch) (and use await _async_is_gcs_leader(self.gcs_client) in _is_passive_gcs()).

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.

Good catch on the startup race with is_gcs_leader_local()! Fixed by priming the leadership cache once via await _async_is_gcs_leader(self.gcs_client) in DashboardHead.run() before starting dashboard_head_modules

Comment thread python/ray/_private/log_monitor.py Resolved
@rueian rueian self-assigned this Oct 6, 2026
@YoyinZyc
YoyinZyc force-pushed the passive_python_head branch from 19108ef to 501bb48 Compare October 15, 2026 20:56

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

@YoyinZyc

Copy link
Copy Markdown
Contributor Author

Thank you @andrewsykim @jhasm @ryanaoleary for the review. I addressed you comments in 501bb48. Please take another look. Thanks!

Comment thread python/ray/autoscaler/v2/monitor.py Resolved
@YoyinZyc

Copy link
Copy Markdown
Contributor Author

Thank you Rueian for the approval, will definitely address your concerns in my next pr.

@rueian
rueian enabled auto-merge (squash) October 21, 2026 18:15
@github-actions github-actions Bot added the go add ONLY when ready to merge, run all tests label Oct 21, 2026
auto-merge was automatically disabled October 23, 2026 21:52

Head branch was pushed to by a user without write access

@YoyinZyc
YoyinZyc force-pushed the passive_python_head branch from 5c4002d to 5213744 Compare October 23, 2026 21:52
@YoyinZyc

Copy link
Copy Markdown
Contributor Author

@rueian the auto merge was disabled due to my last rebase for merge conflict. Can you please stamp it again?

@rueian
rueian enabled auto-merge (squash) October 23, 2026 23:58
@ryanaoleary

Copy link
Copy Markdown
Contributor

@YoyinZyc think this will need another rebase first due to the node.py conflict and then I can enable auto-merge

auto-merge was automatically disabled October 27, 2026 18:09

Head branch was pushed to by a user without write access

@YoyinZyc
YoyinZyc force-pushed the passive_python_head branch from 5213744 to 8836796 Compare October 27, 2026 18:09
Introduce a dedicated exception for passive GCS refusals to distinguish
them from generic transport failures.

Changes:
- Add `GcsPassiveError`, subclassing `RpcError`.
- Map `StatusCode::GcsPassive` to `GcsPassiveError` in `check_status()`.

Considerations:
- Semantic clarity: Differentiate expected standby rejections from GCS crashes
  or network partitions without fragile string matching.
- Backward compatibility: Subclassing `RpcError` preserves existing callers
  and fallback logic (e.g., `is_gcs_leader()` caching).

Signed-off-by: Yuchen Zhou <[email protected]>
Allow `ray start --head` to boot successfully as a standby node without
crashing on mutating internal KV RPC rejections.

Changes:
- Catch `GcsPassiveError` in `_write_cluster_info_to_kv()` and `webui:url`
  registration, allowing startup to proceed.
- Sequence RocksDB session-name marker file creation after the GCS write.
- Re-raise errors when `RAY_ENABLE_GCS_LEADER_ELECTION` is disabled.

Considerations:
- Direct probe over cached check: Catching the write rejection avoids race
  conditions with `is_gcs_leader()`, whose client cache initializes to false
  and could falsely suppress writes on an active leader.
- Safe rollback: Guarding with `RAY_ENABLE_GCS_LEADER_ELECTION` guarantees
  zero behavioral changes when leader election is turned off.

Signed-off-by: Yuchen Zhou <[email protected]>
Suppress log flooding in log monitor when log publishing is rejected by a
passive GCS.

Changes:
- Catch `GcsPassiveError` on GCS publish rejections in `LogMonitor`.
- Use a latch mechanism to log transitions once per direction rather than per batch.
- Drop rejected batches and continue advancing file consumption while passive.
- Clear the latch and restore normal logging on the first accepted publish.

Considerations:
- Prevent log storms: Avoid writing full tracebacks and payload dumps into
  `log_monitor.log` on every rejected publish.
- Continuous loop vs. parking: Parking would incur periodic `is_gcs_leader()`
  RPC overhead and leave file offsets at zero, causing massive publish storms
  upon promotion.
- Safe dropping: Dropping rejected batches is safe because logs are preserved
  on disk and drivers do not subscribe to a passive GCS.

Signed-off-by: Yuchen Zhou <[email protected]>
…CS is passive

Keep autoscaler monitors (v1 & v2) running in standby mode when GCS is passive
and seamlessly take over upon promotion.

Changes:
- Catch passive GCS rejections during startup KV registrations
  (`AutoscalerMetricsAddress`, `DEBUG_AUTOSCALING_ERROR` cleanup).
- Check `is_gcs_leader()` at the start of each update loop pass, idling while passive.
- Replay `AutoscalerMetricsAddress` registration and reset failure state once on promotion.
- Add robust error retry handling to autoscaler v2 loop.

Considerations:
- Prevent split-brain cloud operations: Cloud provider mutations are outside GCS
  gating; explicitly checking leadership prevents an inactive head from launching
  or killing nodes.
- Probe strategy: One-shot startup uses rejection handling to avoid cache lag; the
  recurring loop uses `is_gcs_leader()` where a temporary false negative only skips
  a benign tick.
- Accurate status reporting: Replaying metrics address on promotion ensures
  `ray status` points to the active autoscaler endpoint.

Signed-off-by: Yuchen Zhou <[email protected]>
Prevent Dashboard head and agent crashes when registering addresses against
a passive GCS.

Changes:
- Catch passive GCS rejections during initial KV address registrations in both
  head and agent.
- Dashboard agent retries until its node-specific address registration succeeds.
- Dashboard head monitors leadership cache in `_register_addresses_loop()` and
  registers its addresses upon promotion.
- Replay deferred keys (`webui:url`, `session_name`) upon promotion.
- Switch `DASHBOARD_ADDRESS` registration to `async_internal_kv_put`.

Considerations:
- Protect standby node viability: Because Dashboard agent is fate-shared with
  raylet, failing registration would crash the entire standby node.
- Zero-overhead leadership polling: Dashboard head leverages existing
  `_gcs_check_alive()` cache to detect promotion without dedicated RPCs.
- Idempotent session recovery: Replaying `session_name` with `overwrite=False`
  ensures workers can connect while preserving the original session if already set.

Signed-off-by: Yuchen Zhou <[email protected]>
Prevent `ray start --head` from blocking or losing dashboard process tracking
when starting with a passive GCS.

Changes:
- In `start_api_server()`, skip polling `DASHBOARD_ADDRESS` when GCS is passive
  and return `process_info` immediately.
- In `Node`, skip writing `webui:url` when GCS is known to be passive.

Considerations:
- Avoid startup timeout & zombie process tracking: Since a passive dashboard
  defers publishing its address, polling would block for 60s and swallow errors,
  returning `process_info=None` and dropping the spawned dashboard from process
  supervision.
- Reuse explicit rejection signals: Use the rejection outcome from
  `_write_cluster_info_to_kv()` rather than `is_gcs_leader()` to eliminate cold-start
  cache inaccuracies.
- Ensure supervisor coverage: Returning valid `process_info` allows KubeRay's
  blocking liveness monitor (`dead_processes()`) to properly supervise the dashboard.

Signed-off-by: Yuchen Zhou <[email protected]>
Ensure cluster metadata and telemetry reporting remain correct and consistent
across head promotion and rolling upgrades.

Changes:
- Replay and overwrite `CLUSTER_METADATA` from Dashboard head upon promotion.
- Invalidate persistent caching of cluster metadata in `ReporterHead`.
- Restrict `UsageStatsHead` reporting to active leader state; share GCS client
  leadership cache from head service.
- Return `None` from `get_cluster_metadata()` instead of raising `AttributeError`
  when metadata key is missing.

Considerations:
- Support rolling upgrades: Overwriting `CLUSTER_METADATA` on promotion ensures
  subsequent workers validate versions against the currently active head rather
  than a stale/upgraded predecessor.
- Prevent duplicate empty telemetry: Silences standby usage reporters that would
  otherwise query gated GCS APIs and dispatch empty telemetry payloads.
- Worker resilience: Gracefully handle absent metadata to allow workers to join
  safely before promotion writes finish.

Signed-off-by: Yuchen Zhou <[email protected]>
…e GCS refuses writes

Introduce common passive GCS utilities and fortify NodeHead and head services
against passive write rejections.

Changes:
- Add `ray._private.gcs_passive_utils` with `is_refused_by_passive_gcs`,
  `PassiveLatch`, and `wait_until_gcs_leader`.
- In `NodeHead`:
  - Pause node and actor update subscriptions until promoted via `wait_until_gcs_leader`.
  - Commit `head_node_id` only after KV put succeeds.
  - Ignore passive refusals when cleaning up dead node agent addresses.
  - Guard `_update_nodes` against per-node processing failures.
- In `EventAgent` and `ReporterAgent`, adopt `PassiveLatch` to mute per-second log spam.
- In `dashboard/consts.py`, define `HEAD_PROMOTION_REPLAY_KEYS` contract; replay
  `tracing_startup_hook` and bulk extra usage tags upon promotion.

Considerations:
- Prevent poisoned state: Recording `head_node_id` before KV confirmation leaves
  memory state desynchronized from GCS.
- Loop fault isolation: Individual node processing errors must not abort the
  cluster-wide node update stream.
- Centralized promotion contract: Explicitly declares all KV keys that must be
  replayed upon failover to prevent state divergence.

Signed-off-by: Yuchen Zhou <[email protected]>
Consolidate passive GCS checks, edge-triggered logging, and KV helpers across
all head components into `gcs_passive_utils`.

Changes:
- In `gcs_passive_utils.py`:
  - Centralize refusal detection in `is_refused_by_passive_gcs(exc, latch=None)`.
  - Provide unified sync/async helpers (`put_kv_passive_safe`, `del_kv_passive_safe`, etc.)
    supporting latch updates, custom loggers, and context warnings.
- Refactor call sites across `head.py`, `agent.py`, `monitor.py` (v1/v2),
  `log_monitor.py`, `usage_stats_head.py`, `node_head.py`, and `node.py` to use
  shared utilities.
- Add unit tests in `test_gcs_passive_utils.py`.

Considerations:
- DRY & consistency: Eliminate scattered try/except boilerplates and disparate flag
  tracking across subsystems.
- Maintainability & testability: Centralize passive refusal semantics and edge-triggered
  logging behavior into a single, thoroughly tested utility module.

Signed-off-by: Yuchen Zhou <[email protected]>
- Pass --gcs-is-passive to Dashboard subprocess to guarantee promotion
  replay contract runs even if promoted during dashboard boot.
- Simplify Agent address registration with async_put_kv_passive_safe and
  short-circuiting logic, avoiding unretrieved gather exceptions.
- Use short-circuiting and in Dashboard _resume_after_promotion to avoid
  redundant KV writes on passive rejections.
- Use inspect.isawaitable in _async_is_gcs_leader to properly await
  asyncio.Future returned by Cython GcsClient.async_check_alive.
- Concurrently replay recorded extra usage tags with asyncio.gather in
  async_put_recorded_extra_usage_tags.
- Gracefully handle missing cluster metadata in generate_report_data.
- Harden node update error logging in NodeHead against unexpected payloads.
- Add unit tests covering late-promotion replay, flag forwarding,
  Future awaitable handling, and missing metadata.

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

- Write empty webui:url on promotion when serve_frontend is False to match
  services.start_api_server().
- Prime leadership cache via _async_is_gcs_leader in DashboardHead.run()
  before starting modules that read is_gcs_leader_local() on startup.
- Keep autoscaler promotion latch pending until takeover writes succeed,
  skip scaling passes on demotion races, and fail fast on non-passive errors.
- Narrow _async_is_gcs_leader exception handling to (RpcError, GetTimeoutError).
- Update and add unit tests covering frontend-disabled replay, takeover
  failure/demotion races, and leadership probe exceptions, and move inline
  test imports to the top of the file.

Signed-off-by: Yuchen Zhou <[email protected]>
@YoyinZyc
YoyinZyc force-pushed the passive_python_head branch from 8836796 to e3abeba Compare October 27, 2026 20:09
@YoyinZyc

Copy link
Copy Markdown
Contributor Author

@ryanaoleary rebased

@ryanaoleary
ryanaoleary enabled auto-merge (squash) October 27, 2026 22:03
@rueian

rueian commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

cc @edoakes to merge. 🙏

@YoyinZyc

YoyinZyc commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@rueian @edoakes can we merge the pr?

@edoakes
edoakes disabled auto-merge November 4, 2026 19:59
@edoakes
edoakes merged commit 1fec8a8 into ray-project:master Nov 4, 2026
7 checks passed
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.

6 participants