Repository navigation
[Active-Passive] Phase 2.4 Adjust the components on head node to be compatible with passive setup - #66635
Conversation
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
7b05608 to
ebc7cee
Compare
ebc7cee to
19108ef
Compare
|
@ryanaoleary @rueian @jhasm This PR is for the subprocesses running on the head node. Please take a look if you have time. Thanks! |
There was a problem hiding this comment.
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.
| 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(): |
There was a problem hiding this comment.
_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.
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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:
- In C++ (
NodeInfoAccessor::NodeInfoAccessorinsrc/ray/gcs_rpc_client/accessor.cc),is_gcs_leader_is initialized to!RayConfig::instance().ENABLE_GCS_LEADER_ELECTION()— i.e.,falsewhenRAY_ENABLE_GCS_LEADER_ELECTION=1. It is only updated once aCheckAliveRPC response arrives (AsyncCheckAlivecallback). - In
DashboardHead.run(),self.gcs_client = GcsClient(...)is instantiated and noCheckAlivecall is made before startingconcurrent_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)
- On the first event-loop turn:
self._gcs_check_alive()callsawait 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. Whenself.usage_stats_enabledisFalse, it does not sleep and immediately callsawait self._report_disabled_usage_async()._report_disabled_usage_async()synchronously callsself._is_passive_gcs(), which readsself.gcs_client.is_gcs_leader_local()before the in-flightasync_check_alive()RPC can complete.
- In C++ (
- Impact:
- Even on an active leader head node, when
RAY_ENABLE_GCS_LEADER_ELECTION=1andusage_stats_enabled=False,self.gcs_client.is_gcs_leader_local()is guaranteed to read the unprimedFalsecache value. _is_passive_gcs()returnsTrue, logs a false warning ("GCS is in passive mode. Skipping the usage report until promoted."), andUsageStatsHead.run()immediatelyreturns — permanently skipping the disabled-usage report.- Furthermore, on a genuinely passive head that is later promoted, because
UsageStatsHead.run()exits immediately afterawait self._report_disabled_usage_async(), the disabled-usage report is never sent after promotion either (and ifRAY_USAGE_STATS_REPORT_INTERVAL_Sis set small in tests, the first enabled usage report can similarly race the initialCheckAlive).
- Even on an active leader head node, when
- Suggested fix:
- Either prime
await self.gcs_client.async_check_alive(node_ids=[], timeout=...)once inDashboardHead.run()before startingdashboard_head_modules, and/or have_report_disabled_usage_async()wait viaawait wait_until_gcs_leader(self.gcs_client, latch=self._usage_passive_latch)(and useawait _async_is_gcs_leader(self.gcs_client)in_is_passive_gcs()).
- Either prime
There was a problem hiding this comment.
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
19108ef to
501bb48
Compare
|
Thank you @andrewsykim @jhasm @ryanaoleary for the review. I addressed you comments in 501bb48. Please take another look. Thanks! |
|
Thank you Rueian for the approval, will definitely address your concerns in my next pr. |
Head branch was pushed to by a user without write access
5c4002d to
5213744
Compare
|
@rueian the auto merge was disabled due to my last rebase for merge conflict. Can you please stamp it again? |
|
@YoyinZyc think this will need another rebase first due to the node.py conflict and then I can enable auto-merge |
Head branch was pushed to by a user without write access
5213744 to
8836796
Compare
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]>
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]>
8836796 to
e3abeba
Compare
|
@ryanaoleary rebased |
|
cc @edoakes to merge. 🙏 |
Description
Under the Active-Passive GCS architecture (
RAY_ENABLE_GCS_LEADER_ELECTION=true), a passive GCS instance rejects all mutating RPCs withStatusCode::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(defaultFalse), ensuring zero behavioral impact when leader election is disabled.Key Changes (by Subsystem)
1. Core Exception & Centralized Passive Utilities
GcsPassiveError): SubclassesRpcErrorto distinguish expected passive GCS write refusals from fatal network partitions or GCS crashes without relying on fragile error string parsing.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.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)_write_cluster_info_to_kv()catchesGcsPassiveErrorand allows node initialization to continue without writing initial cluster info.start_api_server()skips polling forDASHBOARD_ADDRESSwhen GCS is passive and returnsprocess_infoimmediately. This prevents a 60-second stall and avoids dropping the dashboard from KubeRay’sdead_processes()liveness supervisor.webui:urlto GCS since the URL is deferred until promotion.3. Dashboard Head, Agents & Promotion Replay Contract
_register_addresses_loop()(leveraging existing_gcs_check_alive()cache without extra RPCs).HEAD_PROMOTION_REPLAY_KEYS): Defined indashboard/consts.pyto 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).EventAgentandReporterAgentusePassiveLatchto mute repetitive registration failures while waiting for promotion.4. NodeHead Subprocess
wait_until_gcs_leader()to pause node and actor update subscriptions until promoted._registered_head_node_idonly after the KV put succeeds to prevent poisoned in-memory state on write rejections._delete_agent_addresses) ignores passive GCS refusals._update_nodesso a single malformed entry does not terminate the subscription loop.5. Autoscaler Monitors (v1 & v2)
AutoscalerMetricsAddressregistration andDEBUG_AUTOSCALING_ERRORcleanup.is_gcs_leader()before each pass, remaining idle while passive. This prevents passive heads from issuing unauthorized node launches or terminations to cloud providers.AutoscalerMetricsAddressand clears stale error status soray statusreflects the newly active autoscaler.6. Log Monitor
GcsPassiveErroron rejected log publish batches and usesPassiveLatchto log state transitions once.is_gcs_leader()polling and prevents massive re-reading/publishing log storms upon promotion.7. Usage Stats & Telemetry
UsageStatsHeadreporting to active leaders, preventing duplicate empty telemetry reports under the same session ID.get_cluster_metadata()returnsNoneinstead of raisingAttributeErrorwhen the key has not yet been written, allowing early joining workers to connect safely.###GCS
internal_kvKey Handling StrategiesBecause different cluster state keys have distinct consistency requirements and lifecycles, mutating operations on GCS
internal_kvare categorized into explicit synchronization strategies:session_nameKV_NAMESPACE_SESSION(
"session")(
overwrite=False)Node._write_cluster_info_to_kv()catches write refusal and skips; startup continues.DashboardHeadwithoverwrite=False.CLUSTER_METADATAKV_NAMESPACE_CLUSTER(
"cluster")(
overwrite=True)Nodecatches write refusal and skips. Readers returnNoneinstead of raisingAttributeError.DashboardHeadwithoverwrite=True;ReporterHeadstops permanently caching it.DASHBOARD_ADDRESSKV_NAMESPACE_DASHBOARD(
"dashboard")(
overwrite=True)DashboardHeaddefers registration;start_api_server()skips polling and returnsprocess_infoimmediately.DashboardHeadwithoverwrite=True.RAY_DASHBOARD_STARTUP_TIMEOUT_S. Returning validprocess_infoprevents KubeRay'sdead_processes()monitor from losing track of the spawned dashboard.webui:urlKV_NAMESPACE_DASHBOARD(
"dashboard")(
overwrite=True)Nodeskips writingwebui:urlupon detecting a passive GCS.DashboardHeadwithoverwrite=True.DashboardMetricsAddressNone(default)(
overwrite=True)DashboardHeadcatches write refusal and suppresses registration.DashboardHeadwithoverwrite=True.tracing_startup_hookKV_NAMESPACE_TRACING(
"tracing")(
overwrite=True)Nodeskips initial registration if GCS is passive.DashboardHeadwithoverwrite=True(if configured on startup).extra_usage_tag_*(e.g.
AUTOSCALER_VERSION)KV_NAMESPACE_USAGE_STATS(
"usage_stats")async_put_recorded_extra_usage_tags()bulk replays all buffered tags upon promotion.AutoscalerMetricsAddressNone(default)(
overwrite=True)PassiveLatchmutes repeat logs.overwrite=True.ray statusand monitoring tools query the active autoscaler rather than the dead predecessor.DEBUG_AUTOSCALING_ERRORNone(default)_resume_after_promotion()upon taking over.DEBUG_AUTOSCALING_STATUSNone(default)is_gcs_leader()before each pass; completely idles while passive.DASHBOARD_AGENT_ADDR_NODE_ID_PREFIX*DASHBOARD_AGENT_ADDR_IP_PREFIX*KV_NAMESPACE_DASHBOARD(
"dashboard")(Node-scoped, no replay)
DashboardAgentcatches refusal and retries registration in background until accepted.KV_NAMESPACE_DASHBOARD(
"dashboard")(Refusal safely ignored)
NodeHeadcallsasync_internal_kv_del; passive refusals are caught and ignored.head_node_idKV_NAMESPACE_JOB(
"job")(
overwrite=True)NodeHeadwhen head node becomes ALIVE._registered_head_node_idis 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):
####3. Manual test: Standby Behavior Verification
Started a dual-head local cluster with Node A as active leader and Node B as passive standby
Related issues
#63643