Skip to content

[core][gcs] Add embedded RocksDB storage backend for GCS fault tolerance (REP-64) - #63657

Merged
edoakes merged 48 commits into
ray-project:masterfrom
jhasm:jhasm/rep-64-rocksdb-store-client
Jul 11, 2026
Merged

edoakes merged 48 commits into
ray-project:masterfrom
jhasm:jhasm/rep-64-rocksdb-store-client

Conversation

@jhasm

@jhasm jhasm commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements the embedded RocksDB storage backend for GCS fault tolerance proposed in REP-64.

Today, GCS fault tolerance requires an external Redis instance. This PR adds RocksDB as a second backend, selected via RAY_gcs_storage=rocksdb and RAY_gcs_storage_path=<path-on-pvc>. The recovery model is identical to Redis-backed FT — GCS restarts, reads state from local disk, workers reconnect — only the location of persisted state differs.

KubeRay operator changes (the gcsFaultToleranceOptions.backend: rocksdb field that auto-manages PVCs) are explicitly out of scope here and will land in ray-project/kuberay.

Why a new PR

This is a streamlined version of the POC at #63032. That PR carries the full evidence dossier (phase reports, kill-9 harness, k8s test harness, microbench results — ~10K lines of supporting material) which served its purpose during design review. For the merge PR, only the production code is included; #63032 remains the reference for per-claim reproducibility evidence and the @andrewsykim review thread.

What's in this PR

Commit What
1 bazel/rocksdb.BUILD + bazel/ray_deps_setup.bzl — add RocksDB 9.11.2 as a third-party dependency (static-only, no compression / jemalloc / tools, built via rules_foreign_cc).
2 src/ray/gcs/store_client/rocksdb_store_client.{h,cc} + 4 tests + storage_microbench binary. RocksDB I/O runs on a boost::asio::thread_pool (keeping the WAL fsync off the GCS event loop) with per-key boost::asio::strands bucketed by hash(table, key) for submission-order ordering. WriteOptions::sync = true on every mutating call.
3 Wire it into GcsServer (factory dispatch in InitClusterStorageBackend + InitKVManager, 3 new config flags, node.py session-name sidecar for restart recovery, raylet startup wait bumped 30 → 60s on rocksdb).
4 TEST_GCS_ROCKSDB=1 fixture toggle in python/ray/tests/conftest.py — existing cluster fixtures auto-dispatch.
5 New postmerge buildkite jobs :ray: core: rocksdb tests + :ray: core: out of disk rocksdb tests, mirroring the Redis FT jobs.
6 Docs: new K8s setup page (kuberay-gcs-rocksdb-ft.md) + an "Embedded RocksDB backend" section in gcs.rst.
7 Review follow-ups: remove the inline execution path and the gcs_rocksdb_async_offload toggle so RocksDB I/O always offloads; make GetNextJobIDSync private (tests drive it through the public AsyncGetNextJobID); extract the rocksdb session-name marker logic in node.py into its own helper; collapse storage_microbench to a single rocksdb backend; make the soft-durable table set a hardcoded, documented constant (SoftDurableTables()) instead of the gcs_rocksdb_soft_durability_tables config flag, since it's a fixed design property rather than an operator knob.

Aggregate: +2,973 / -20 across 26 files. All commits signed off (DCO).

REP-64 acceptance criteria

  1. Release tests pass with RAY_gcs_storage=rocksdb — the new postmerge job runs the standard test suite under the rocksdb backend.
  2. New postmerge CI job mirroring Redis GCS FT — ✓ commit 5.
  3. Scale tests at parity with Redis — covered by the postmerge job's //python/ray/tests/... target set (includes test_many_actors.py).
  4. Serve chaos passes — covered by the postmerge job.

Tests

C++ unit tests under src/ray/gcs/store_client/tests/:

  • rocksdb_smoke_test — Bazel-integration sanity (open / put / get).
  • rocksdb_store_client_test — RocksDb-specific scenarios: recovery across close+reopen, cluster-id marker fail-fast, pool-thread write roundtrip.
  • rocksdb_parity_test — runs the full StoreClientTestBase suite (same fixture as in_memory_store_client_test and redis_store_client_test).
  • rocksdb_concurrency_test — per-key strand correctness + JobID-counter atomicity under N-thread contention.

Python integration coverage: the existing //python/ray/tests/... / //python/ray/dag/... / //python/ray/autoscaler/v2/... suites run under TEST_GCS_ROCKSDB=1 via the new buildkite jobs.

The local k3d cluster recovery test harness from the POC branch was repeated on this branch. Results and reproduction instructions are in doc REP-64 RocksDB GCS — Kubernetes Recovery: Evidence of Correctness & Reproduction Guide

Out of scope (follow-ons)

  • KubeRay operator support for gcsFaultToleranceOptions.backend: rocksdb — separate ray-project/kuberay PR.
  • PVC stale-data fail-fast via K8s downward API (RAY_CLUSTER_ID env-injected cluster-id marker) — RocksDbStoreClient already supports the check; needs the KubeRay-side plumbing.
  • Remove the soft-durability workaround. The soft-durability relaxation added here (skipping the per-write WAL fsync on the NODE/ACTOR death-notification tables, now a hardcoded SoftDurableTables() constant) works around a GCS-core object-reconstruction / task-resubmission race that RocksDB's fsync latency widens. That race was proven to be rooted in the GCS code (see [DO NOT MERGE][core][gcs] Provenance: node-death lost-wakeup hangs generator reconstruction (REP-64) #64187). A follow-on PR will fix the root cause in GCS and remove this workaround so every table keeps strict per-write fsync.
  • macOS / Windows support (targets currently gated on @platforms//os:linux).

References

@jhasm
jhasm requested a review from a team as a code owner May 27, 2026 03:08

@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 an embedded RocksDB storage backend for GCS fault tolerance (REP-64) as an alternative to external Redis. It includes the Bazel build setup, a C++ RocksDbStoreClient implementation, integration into the GCS server, Python sidecar file management for session recovery, and comprehensive test suites. The review feedback identifies two critical issues: a type mismatch in Python where the session name is read as raw bytes instead of a decoded UTF-8 string (which would break recovery comparisons), and a performance bottleneck in C++ where exclusive locks are acquired on every column family lookup instead of utilizing a reader-writer lock for the fast path.

Comment thread python/ray/_private/node.py Resolved
Comment thread python/ray/_private/node.py Resolved
jhasm added a commit to jhasm/ray that referenced this pull request May 27, 2026
…-kv_put

- rocksdb_store_client: steady-state column-family lookups now take a
  shared absl::ReaderMutexLock; the exclusive lock is only acquired on
  first-touch when creation is needed. Hot path (every Get/Put/Delete)
  no longer serializes through one mutex.

- node.py write_cluster_metadata: persist the RocksDB session_name
  sidecar BEFORE internal_kv_put. If we crashed between kv_put and
  sidecar write under the previous ordering, the next restart found no
  sidecar, generated a new session_name, and tripped the kv-put
  assertion. The new ordering closes that window: a crash between
  sidecar-write and kv-put leaves the sidecar's name as the source of
  truth and kv_put inserts it cleanly on restart.

Both fixes address bot review comments on PR ray-project#63657.

Signed-off-by: Santosh Jha <[email protected]>
jhasm added a commit to jhasm/ray that referenced this pull request May 27, 2026
- rocksdb_store_client.cc: move <sys/stat.h> to its own block above the
  standard library headers (clang-format violation existed since the
  file's introduction).
- node.py: black collapsed two os.path.join() calls onto single lines.

Fixes ./ci/lint/lint.sh clang_format and ./ci/lint/lint.sh pre_commit
on PR ray-project#63657.

Signed-off-by: Santosh Jha <[email protected]>
Comment thread python/ray/_private/node.py Resolved
Comment thread python/ray/_private/node.py Resolved
@ray-gardener ray-gardener Bot added docs An issue or change related to documentation core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels May 27, 2026
Comment thread bazel/ray_deps_setup.bzl Outdated
auto_http_archive(
name = "com_github_facebook_rocksdb",
build_file = "@io_ray//bazel:rocksdb.BUILD",
url = "https://github.com/facebook/rocksdb/archive/refs/tags/v9.11.2.tar.gz",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can't we use the latest racksdb?

@jhasm jhasm May 27, 2026 •

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.

Bumped to v10.6.2 in 874639a.

Couldn't go all the way to v11.x: RocksDB 10.7.0 (Sep 2025, release notes) raised the minimum to C++20 for both the library and any code including its headers (GCC ≥ 11, Clang ≥ 10, MSVC ≥ 2019). Ray's .bazelrc pins -std=c++17, so bumping past 10.6.2 would require a coordinated Ray-wide C++20 migration.

v10.6.2 is the newest C++17-compatible release. Constraint documented inline in bazel/ray_deps_setup.bzl so the next bumper sees the cliff.

```

GCS metadata is small (typically 10–100 MB across all column families
in steady state); 1 GiB is ample headroom.

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.

Maybe we should also add a disclaimer saying that storage size can affect IOPS on cloud providers.

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 call — added an IOPS-on-cloud-providers note under the PVC step in 874639a. Covers AWS gp2/gp3, GCE pd-balanced, Azure Premium SSD v1/v2.

@edoakes edoakes added the go add ONLY when ready to merge, run all tests label May 27, 2026
@edoakes

edoakes commented May 27, 2026

Copy link
Copy Markdown
Collaborator

Kicked off premerge tests: https://buildkite.com/ray-project/premerge/builds/67178

Comment thread .buildkite/core.rayci.yml Outdated
tags:
- python
- oss
- skip-on-premerge

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

let's make these tests conditionally run on premerge if anything under gcs/store_client/ is modified (we can do the same for the redis tests actually)

here is a PR where I did it previously for some python code: #53056

@jhasm jhasm May 27, 2026 •

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.

Done in 874639a following the spark_on_ray pattern from #53056.

Declared rocksdb_tests + redis_tests in .buildkite/test.rules.txt, with a rule that emits both for src/ray/gcs/store_client/ and bazel/rocksdb.BUILD (rule placed before the broad src/ catch-all so it wins; broad tags are also emitted to preserve build coverage). Swapped skip-on-premerge → the new tags on both the main and out-of-disk rocksdb/redis blocks in .buildkite/core.rayci.yml. Postmerge unchanged (master sets RAYCI_RUN_ALL_TESTS=1). Validated rule-match via ci/pipeline/determine_tests_to_run.py; this push itself will exercise the new gating since it touches both paths.

jhasm added a commit to jhasm/ray that referenced this pull request May 27, 2026
…ional CI, IOPS doc, sidecar guards

Bundle of four targeted fixes from the first human-reviewer round:

* bazel/ray_deps_setup.bzl: bump RocksDB v9.11.2 -> v10.6.2 (@rueian).
  v10.6.2 is the newest release that still defaults to C++17. RocksDB
  10.7.0 (Sep 2025) raised the minimum compiler standard to C++20 for
  both the library and any code including its headers; Ray's .bazelrc
  pins -std=c++17, so future bumps past 10.6.2 require a coordinated
  C++20 migration. Constraint documented inline so the next bumper
  sees it.

* .buildkite/test.rules.txt + core.rayci.yml: gate the rocksdb / redis
  GCS FT premerge suites on changes under src/ray/gcs/store_client/
  and bazel/rocksdb.BUILD (@edoakes). Follows the spark_on_ray pattern
  introduced in ray-project#53056: declare new rocksdb_tests / redis_tests tags,
  emit them from a path rule that also includes the broad src/ tag set
  so build coverage is unchanged, and replace skip-on-premerge on both
  the main and out-of-disk rocksdb / redis blocks with the new tags.
  Postmerge unchanged because master pushes set RAYCI_RUN_ALL_TESTS=1.

* doc/source/cluster/kubernetes/user-guides/kuberay-gcs-rocksdb-ft.md:
  add an IOPS-on-cloud-providers callout under the PVC step (@rueian)
  noting that AWS gp2, GCE pd-balanced, and Azure Premium SSD v1 scale
  baseline IOPS with provisioned size, so a 1 GiB volume sized for
  GCS metadata footprint can throttle RocksDB's per-write fsync.

* python/ray/_private/node.py: raise ValueError in both
  check_persisted_session_name and _write_cluster_info_to_kv when
  RAY_gcs_storage=rocksdb but RAY_gcs_storage_path is empty
  (cursor[bot]). Mirrors the C++ RAY_CHECK in gcs_server.cc::
  GetStorageType() so the Python path fails loudly instead of
  silently skipping sidecar recovery -- which would generate a fresh
  session_name on restart and trip the persisted-name assert.

Signed-off-by: Santosh Jha <[email protected]>
Comment thread python/ray/_private/node.py Resolved
Comment thread python/ray/_private/node.py Resolved
Comment thread python/ray/tests/conftest.py Resolved
Comment thread python/ray/_private/node.py Resolved
jhasm added a commit to jhasm/ray that referenced this pull request May 29, 2026
The assert in _write_cluster_info_to_kv hardcoded "error connecting to
Redis" in its failure message, but this code path now also backs the
RocksDB GCS storage backend. On a sidecar <-> internal_kv divergence
under RocksDB, the message pointed operators at the wrong subsystem.
Reword to "error connecting to the GCS storage backend".

Addresses cursor[bot] review on PR ray-project#63657. (The same comment's
"sidecar returns bytes" claim is a non-op: check_persisted_session_name
returns bytes and the call site decodes via ray._common.utils.decode,
in parity with the Redis path.)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Santosh Jha <[email protected]>
Comment thread python/ray/_private/node.py Outdated
start_time = time.monotonic()
raylet_start_wait_time_s = 30
default_wait = (
"60" if os.environ.get("RAY_gcs_storage") == "rocksdb" else "30"

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.

Is this really needed? We should already make sure GCS is ready at this point.

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.

Apparently it is, and I had to change this to 60 as 30 was flaky for rocksdb, for the tests with high number of records (e.g. 100k) in rocksdb. For the fresh start cases (not crash recovered head node), you are probably right that we may not need to wait this long.

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.

Actually, reverted to 30s in 172fd4f. I was mistaken about the large db test being related to this one. I checked the commit history and that is not the case.

Unlike the port-file wait below, this one wasn't tied to an actual failure; I'd added it preemptively to absorb GCS state replay, and our storage-layer recovery numbers (cold-open under 100 ms even at 10k keys) don't justify it. I also dropped the Python-side reuse of RAY_raylet_start_wait_time_s - that env name already drives a separate C++ wait in global_state_accessor, so overloading it from here was a mistake.

Comment thread python/ray/_private/node.py Outdated
if self._ray_params.gcs_server_port == 0:
# GCS startup is slower with the RocksDB backend (opens two
# DB instances at /tables and /kv, replays WAL, validates
# cluster-id marker), so the default 30s wait for the port

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.

This path is only for starting a fresh GCS. Can't a fresh RocksDB be ready in 30s?

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.

Right, the RocksDB open itself is cheap our cold-open benchmark is 32/36/73 ms at 100/1k/10k keys. But the port file isn't gated on the open; it's published only at the very end of startup (GcsServer::DoStart -> rpc_server_.Run()), which runs after GcsInitData::AsyncLoad does a GetAll over the full persisted table set (job/node/actor/actor-task-spec/placement-group) and every manager is built.

So there are two costs: a fixed one - two on-disk DB opens (CF discovery, WAL replay, manifest read) plus the cluster-id round-trip, which is what pushed even the small test_ray_address_environment_variable past 30s on a loaded CI runner (commit 6031d86) - and a variable one - those full-table scans, which hit disk and grow with cluster state on restart. wait_for_persisted_port polls every 100 ms and returns the instant the file appears, so the 120s is only a ceiling, not added latency on the happy path. I clarified the comment in 172fd4f and noted the path is reached on head restart too (the port file lives on ephemeral /tmp). Happy to dial 120 -> 60 if you'd prefer a tighter ceiling.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hi @jhasm,

I am confused. In the case of a restart, the port file is already there. Do we still need a longer timeout for wait_for_persisted_port?

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 question — and the short answer is: on the warm restart you're describing (port file still on disk), we don't hit the longer timeout at all. There are two distinct paths:

  1. Warm restart, port file present — start_head (node.py:362–377): if get_port_filename(...) already exists in the session dir we treat it as a GCS restart and read the persisted port instantly via wait_for_persisted_port(..., timeout_ms=0), then set gcs_server_port to that non-zero value.
  2. Bind-and-publish, port file absent — start_gcs_server (node.py:1157): the 30s/120s wait runs only if self._ray_params.gcs_server_port == 0. After path 1 sets a non-zero port, this guard is false and the wait is skipped entirely.

So when the port file is already there, we just read it and move on — the 120s ceiling never applies. It only bites when port == 0, which is:

  • a fresh start (no port file yet), or
  • a restart where the port file was lost. Under KubeRay the port file lives on the pod-local ephemeral /tmp, not on the GCS PVC, so a head-pod restart comes up with a fresh /tmp (no port file) but a fully-populated RocksDB store on the PVC. GCS then has to replay the full persisted table set (GetAll over job/node/actor/actor-task-spec/placement-group) before rpc_server_.Run() binds and publishes the port — and that replay is what can exceed 30s on a loaded runner with non-trivial cluster state.

It's a poll-every-100ms ceiling, so it adds no latency on the happy path; it just avoids a spurious timeout on the cold-/tmp/large-store case. Happy to (a) make this two-path distinction explicit in the comment so it's not conflated with the warm restart, and/or (b) dial the ceiling 120 → 60 if you'd prefer a tighter bound. Which would you like?

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.

Thanks for the clarification. 👍 The current timeout is fine.

Comment thread python/ray/_private/node.py Outdated
"RAY_gcs_storage=rocksdb requires RAY_gcs_storage_path "
"to be set to a writable directory."
)
session_name_file = os.path.join(rocksdb_storage_path, ".session_name")

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.

Suggested change
session_name_file = os.path.join(rocksdb_storage_path, ".session_name")
session_name_file = os.path.join(rocksdb_storage_path, "session_name")

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.

Done in cb6b24c renamed to session_name (dropped the leading dot) at the read site, the write site, and the temp-file prefix so all three stay consistent. No behavior change beyond the on-disk filename.

Comment thread python/ray/_private/node.py Outdated
"RAY_gcs_storage=rocksdb requires RAY_gcs_storage_path "
"to be set to a writable directory."
)
session_name_file = os.path.join(rocksdb_storage_path, ".session_name")

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.

Suggested change
session_name_file = os.path.join(rocksdb_storage_path, ".session_name")
session_name_file = os.path.join(rocksdb_storage_path, "session_name")

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.

Done in cb6b24c renamed to session_name (dropped the leading dot) at the read site, the write site, and the temp-file prefix so all three stay consistent. No behavior change beyond the on-disk filename.

Comment thread python/ray/_private/node.py Outdated
# file written by the previous head process. GCS isn't up yet at
# this point in startup, so we can't query the rocksdb-backed
# internal_kv directly; the sidecar bridges that gap. Falls
# through to the Redis path below for non-rocksdb deployments.

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.

I think we need an interface for check_persisted_session_name/persist_session_name, though. The current implementation is not cohesive enough with the part in _write_cluster_info_to_kv. Maybe in a follow-up.

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.

Agreed they're asymmetric - the write path is inline in _write_cluster_info_to_kv while the read path is its own method. To keep this PR focused I'll prefer the persist_session_name() / check_persisted_session_name() interface as the follow-up you suggested rather than reshuffling it here.

@jhasm
jhasm force-pushed the jhasm/rep-64-rocksdb-store-client branch from a260863 to b34ecd4 Compare June 11, 2026 03:37
jhasm and others added 2 commits July 11, 2026 04:27
The embedded RocksDB inside the GCS process used RocksDB's per-column-family
default memory (a 64 MiB write buffer and an independent block cache each).
With ~10 GCS column families this let the DB reserve gigabytes of memtables
plus block cache for a workload that is only 10-100 MB. On a memory-constrained
node this OOM-kills the GCS process, which drops every driver/worker in the
cluster.

This is why the core test test_channel::test_payload_large (which allocates a
~600 MiB object next to the GCS) failed only under the RocksDB backend, while
passing under the default and external-redis backends.

Cap total memory explicitly and share the budget across every column family
(including those created lazily at runtime): a single 32 MiB LRU block cache
shared by all CFs, and a single 64 MiB WriteBufferManager (charged to the same
cache) bounding total memtable memory regardless of CF count. The per-CF write
buffer is shrunk to 8 MiB to match the small workload.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Santosh Jha <[email protected]>
Head fault-tolerance restarts reuse the existing fixed GCS port (see
Node.__init__), so start_gcs_server()'s extended RocksDB port-file wait --
which is gated on gcs_server_port == 0 -- is skipped. On that path GCS
readiness depends entirely on the _init_gcs_client retry loop, which defaulted
to ~20s (NUM_REDIS_GET_RETRIES=20 x 1s sleep).

RocksDB recovery (opening two on-disk DBs, WAL replay, and GetAll table scans
that grow with cluster state) is slowest exactly on restart and can exceed
that window, failing head startup even though the port-zero path already
allows up to 120s.

Extend the retry window to the same budget as the port-zero path for a RocksDB
head, overridable via the same RAY_gcs_server_port_wait_time_s env var.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Santosh Jha <[email protected]>
Comment thread python/ray/_private/node.py Resolved
RocksDB GCS recovery (open on-disk DBs, WAL replay, GetAll table scans that
grow with cluster state) is slow -- worst on a head restart over existing
state -- and can exceed the default ~20s _init_gcs_client connect window
(NUM_REDIS_GET_RETRIES x ~1s sleep).

This affects any node connecting while the head is reopening RocksDB:
- the head itself, whose fault-tolerance restart reuses a fixed GCS port and
  thus skips start_gcs_server()'s port-file wait (gated on gcs_server_port==0),
  and
- workers/drivers joining during that recovery window.

Extend the retry budget to match the port-zero path (default 120s) whenever
the backend is detectably RocksDB. Workers/drivers whose pods lack
RAY_gcs_storage / RAY_gcs_storage_path can't auto-detect the backend, so also
honor an explicit RAY_gcs_server_port_wait_time_s override on every node.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Santosh Jha <[email protected]>

@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 73ce9ce. Configure here.

Comment thread python/ray/_private/node.py Resolved
Make RAY_gcs_server_port_wait_time_s behave the same in _init_gcs_client's
connect loop as in start_gcs_server()'s port-file wait. Previously the connect
loop used max(NUM_REDIS_GET_RETRIES, override), which floored the value at the
default 20, so an operator could shorten the port-file wait but not this loop.

Now an explicit override is honored exactly (may lengthen or shorten, floored
at one attempt so 0 still tries once). Without an override, a detected RocksDB
backend still extends the window to 120s without shrinking a larger
operator-configured retry count.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Santosh Jha <[email protected]>

@edoakes edoakes left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the excellent contribution, can't wait for ppl to try this out

@edoakes
edoakes merged commit 3d026f5 into ray-project:master Jul 11, 2026
3 checks passed
jhasm added a commit to jhasm/ray that referenced this pull request Jul 15, 2026
The RocksDB GCS store-client tests (rocksdb_store_client_test,
rocksdb_concurrency_test, rocksdb_parity_test) fail under the C++ TSAN
build with data races reported inside RocksDB itself -- e.g.
`rocksdb::MemTable::Add` (memcpy of key/value bytes) racing with
`rocksdb::BytewiseComparatorImpl::Compare` (memcmp during a concurrent
point lookup).

Root cause: RocksDB is built as a static library by an out-of-band CMake
action (bazel/rocksdb.BUILD via rules_foreign_cc), so the
`--copt -fsanitize=thread` / `--per_file_copt` flags in the `tsan` config
never reach it. A TSAN-instrumented GCS test therefore links an
*un*instrumented librocksdb.a. ThreadSanitizer can see the plain
memcpy/memcmp inside RocksDB's lock-free memtable skiplist but not the
acquire/release atomics that publish and observe those bytes, so it
reports false races. Concurrent Put/Get across the store client's I/O
offload pool is a supported RocksDB operation; the reports are missing
happens-before edges, not real races. (`report_atomic_races=0` cannot
suppress them because the racing accesses are byte-wise memcpy/memcmp,
not atomic ops.)

Fix: build RocksDB with its native `WITH_TSAN` CMake option under the
`tsan` config. This adds `-fsanitize=thread` to RocksDB's own compile and
link flags (the RocksDB-blessed way to run it under TSAN), so
ThreadSanitizer understands RocksDB's synchronization and the false
positives disappear. Non-TSAN builds are unaffected: the
`ray_rocksdb_tsan` define is only set by `--config=tsan`, and the
`cache_entries` select() leaves `WITH_TSAN` off otherwise.

Verified locally that RocksDB now compiles with `-fsanitize=thread` under
`--config=tsan` and the test binary links cleanly against the
instrumented librocksdb.a.

Follow-up to ray-project#63657.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Santosh Jha <[email protected]>
jhasm added a commit to jhasm/ray that referenced this pull request Jul 15, 2026
Adds user-facing documentation for the experimental embedded RocksDB GCS
fault-tolerance backend introduced in ray-project#63657, which persists GCS state to a
local RocksDB database on a persistent volume instead of requiring an external
Redis instance.

- ray-core/fault_tolerance/gcs.rst: introduce the two GCS FT backends up front
  and add an "Embedded RocksDB backend (experimental)" section covering the
  recovery model, a Redis-vs-RocksDB comparison, how to enable it
  (RAY_gcs_storage / RAY_gcs_storage_path), the single-writer constraint, and
  advanced tuning knobs.
- cluster/kubernetes/user-guides/kuberay-gcs-rocksdb-ft.md: new step-by-step
  KubeRay how-to (PVC + env vars, recovery verification), wired into the
  user-guides toctree and list.
- kuberay-gcs-ft.md: cross-link the new RocksDB how-to from the Redis page for
  discoverability.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Santosh Jha <[email protected]>
rueian pushed a commit that referenced this pull request Jul 15, 2026
…nd (#64759)

## Why are these changes needed?

After #63657 merged, the C++ ThreadSanitizer (TSAN) build started
reporting data races in the embedded RocksDB GCS backend tests:

- `//src/ray/gcs/store_client/tests:rocksdb_store_client_test`
- `//src/ray/gcs/store_client/tests:rocksdb_concurrency_test`
- `//src/ray/gcs/store_client/tests:rocksdb_parity_test`

The reported races are **inside RocksDB itself**, e.g.:

```
WARNING: ThreadSanitizer: data race
  Write of size 2 by thread T180:
    #1 rocksdb::MemTable::Add(...)                       // memcpy of key bytes
  Previous read of size 2 by thread T182:
    #1 rocksdb::BytewiseComparatorImpl::Compare(...)     // memcmp during a Get
```

### Root cause

RocksDB is built as a static library by an **out-of-band CMake action**
(`bazel/rocksdb.BUILD` via `rules_foreign_cc`). Bazel's `--copt
-fsanitize=thread` and `--per_file_copt` from the `tsan` config only
apply to Bazel-compiled `cc_library` targets — they never reach the
CMake build. As a result, a TSAN-instrumented GCS test links an
**un-instrumented** `librocksdb.a`.

TSAN can intercept the plain `memcpy`/`memcmp` on the key/value bytes
inside RocksDB's lock-free memtable skiplist, but it **cannot see the
acquire/release atomics** RocksDB uses to publish and observe those
bytes (that synchronizing code is uninstrumented). Missing those
happens-before edges, TSAN reports false races.

Concurrent `Put`/`Get` across the store client's I/O offload pool is a
fully supported RocksDB operation, so these are false positives, not
real races. `report_atomic_races=0` (already set in the `tsan` config)
does not suppress them because the racing accesses are byte-wise
`memcpy`/`memcmp`, not atomic operations.

### Fix

Build RocksDB with its native `WITH_TSAN` CMake option under the `tsan`
config. RocksDB's `CMakeLists.txt` handles `WITH_TSAN` by adding
`-fsanitize=thread` to its own compile/link flags — the RocksDB-blessed
way to run it under TSAN. With RocksDB instrumented, ThreadSanitizer
understands its synchronization and the false positives disappear.

- `.bazelrc`: `--config=tsan` now sets `--define=ray_rocksdb_tsan=true`.
- `bazel/rocksdb.BUILD`: a `config_setting` reads that define and a
`cache_entries` `select()` flips `WITH_TSAN=ON` only for TSAN builds.

Non-TSAN builds are unaffected: the define is only set by
`--config=tsan`, and `WITH_TSAN` stays off in the default `select()`
branch. `--config=tsan-clang` inherits the define via `--config=tsan`.

### Verification

Reproduced and verified with the same toolchain CI uses
(`--config=tsan-clang`, clang 14, libc++). All three previously-failing
tests were built under TSAN and run (ASLR disabled via `setarch -R`,
`TSAN_OPTIONS=report_atomic_races=0`, matching CI):

| RocksDB build (clang-14 TSAN, identical otherwise) | Data races |
Result |
| --- | --- | --- |
| **Without this fix** (uninstrumented `librocksdb.a`) | **10** |
**FAILED** (TSAN exits 66) |
| **With this fix** (`WITH_TSAN=ON`) | **0** | **PASSED** |

The negative-control run (fix disabled via
`--define=ray_rocksdb_tsan=false`) reproduces the exact races from the
report — `rocksdb::MemTable::Add` (memcpy) racing
`rocksdb::BytewiseComparatorImpl::Compare` (memcmp) in the memtable
skiplist:

```
SUMMARY: ThreadSanitizer: data race in __interceptor_memcmp
  #1 rocksdb::(anonymous namespace)::BytewiseComparatorImpl::Compare(...) comparator.cc
  #1 rocksdb::MemTable::Add(...)
```

With the fix, the same runs are clean:

```
rocksdb_store_client_test   : 0 data races, [  PASSED  ] 12 tests
rocksdb_concurrency_test    : 0 data races, [  PASSED  ]  4 tests
rocksdb_parity_test         : 0 data races, [  PASSED  ]  2 tests
```

This confirms the fix both eliminates the reported races and that
removing it reproduces them — i.e. the instrumentation is the cause of
the change.

## Related issue number

Follow-up to #63657.

## Checks

- [x] I've signed off every commit (by using the -s flag, i.e., `git
commit -s`) in this PR.
- [x] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
   - [x] Unit tests
   - [ ] Release tests
   - [ ] This PR is not tested :(

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
elliot-barn added a commit that referenced this pull request Jul 16, 2026
…core build) (#64748)

## Why

The aarch64 `wanda: core binary parts py3.{10..14}` postmerge jobs fail
intermittently with:

```
ERROR: .../rules_foreign_cc/toolchains/BUILD.bazel: BootstrapNinjaBuild ... failed
/bin/sh: c++: command not found
```

### Root cause

`bazel/rocksdb.BUILD` (added in #63657, embedded RocksDB GCS backend /
REP-64) builds RocksDB via `rules_foreign_cc`'s `cmake()` with
`generate_args = ["-G Ninja"]`. It's the repo's only foreign_cc target
using the Ninja generator. rules_foreign_cc 0.9.0 has no system ninja,
so it **bootstraps ninja from source**, invoking a bare `c++` under a
scrubbed `PATH=/bin:/usr/bin:/usr/local/bin`. The aarch64 manylinux2014
image has no `c++` on that PATH, so the bootstrap fails.

### Why it's intermittent

The failure only bites on a Bazel **remote-cache miss** for the ninja
tool. Full-suite (release-automation) postmerge history:

| build | commit | aarch64 core |
|-------|--------|--------------|
| 18544 | `914e1a06e1` (parent of #63657) | PASS |
| 18547 / 18549 / 18557 | — | FAIL |
| 18561 | `3ba205c1b0` | PASS (`5932 remote cache hit`, no bootstrap) |
| 18565 / 18567 | — | FAIL |

Cache hit → no bootstrap → pass; cache miss → compile ninja → `c++ not
found` → fail. This becomes a permanent failure once the cache entry is
evicted or invalidated by a config-hash change.

## What

Switch the RocksDB build from the Ninja generator to CMake's Unix
Makefiles generator. Make uses the preinstalled toolchain (as the
jemalloc/openssl foreign_cc builds already do) and needs no source
bootstrap, so the build is deterministic across cache states on every
architecture. Build output (`librocksdb.a`) is unchanged.

Only the ninja *tool bootstrap* was the problem — the RocksDB compile
itself uses Bazel's configured toolchain regardless of generator.

## Notes

- Not caused by, but surfaced alongside, the recent deps-unification
work; independent fix.
- cc the #63657 / REP-64 authors — this is your build rule. If keeping
Ninja is preferred, the alternative is pre-installing `ninja` in the
aarch64 manylinux image (heavier: image rebuild + `MANYLINUX_VERSION`
bump).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
jhasm added a commit to jhasm/kuberay that referenced this pull request Jul 19, 2026
…ance

Add a second GCS fault tolerance backend to KubeRay: the embedded RocksDB
store introduced in ray-project/ray#63657, selected via
`gcsFaultToleranceOptions.backend: rocksdb`. Unlike Redis, RocksDB is linked
into the GCS process, so KubeRay only needs to provision a persistent volume,
mount it on the head Pod, and set a few env vars.

API:
- Add `Backend` discriminator (redis|rocksdb) and `GcsEmbeddedStorage`
  (existingClaim | size/storageClassName/accessModes, subPath) to
  `GcsFaultToleranceOptions`.
- Relax `RedisAddress` from required to optional; validation now enforces it
  for the redis backend (backward compatible, additive CRD change).

Controller:
- Split GCS FT pod wiring into redis/embedded helpers. The embedded path sets
  RAY_gcs_storage=rocksdb, RAY_gcs_storage_path=/data/gcs-state, and a stable
  RAY_CLUSTER_ID (RayCluster UID) marker, and mounts the PVC at /data/gcs-state.
- Add `reconcileGCSStoragePVC`: provisions `{cluster}-gcs-pvc` (GC'd via
  ownerReferences), no-ops for BYO `existingClaim`, and sets the PVC owner to
  the RayService when the RayCluster is service-owned so a zero-downtime
  upgrade does not discard GCS state.
- Add persistentvolumeclaims RBAC (kustomize + Helm chart, kept in sync).

Validation:
- Backend-aware rules: redis requires RedisAddress; rocksdb rejects redis-only
  fields, enforces existingClaim mutual-exclusion, and blocks user-set
  operator-managed env/mounts.

Tests and sample:
- Unit tests for pod wiring, validation, helpers, and the PVC reconciler
  (incl. RayService-owner handling).
- e2e tests in test/e2e: a non-gated wiring test that validates PVC lifecycle
  and head-Pod wiring against any Ray image, and a gated recovery test
  (KUBERAY_TEST_EMBEDDED_GCS_FT=true) that verifies real GCS state recovery
  across a head-Pod restart with a Ray image containing ray#63657.
- Sample `config/samples/ray-cluster.embedded-gcs-ft.yaml`.

Co-authored-by: Copilot <[email protected]>
jhasm added a commit to jhasm/kuberay that referenced this pull request Jul 19, 2026
… persistence, warn on PVC drift

- Remove the RAY_CLUSTER_ID env var and its constant. The upstream Ray embedded
  RocksDB PR (ray-project/ray#63657) never reads RAY_CLUSTER_ID: RocksDbStoreClient
  takes cluster_id as a constructor arg passed empty in production, and
  ValidateOrWriteClusterIdMarker is a no-op when empty (cluster_id-based PVC
  fail-fast is explicitly deferred). Store identity/staleness is handled by Ray's
  persisted session_name marker, with no KubeRay input. The var was dead code and
  the accompanying comment misdescribed shipped Ray behavior.

- Document cross-upgrade persistence and single-writer expectations instead of
  restricting access modes. RocksDB is single-writer; users choose RWO (default,
  standalone RayCluster) or RWX (concurrent attach with externally-coordinated
  single writer). ExistingClaim is the supported path to persist GCS state across
  a RayService zero-downtime upgrade. Updated API field docs, controller comment,
  sample YAML, and regenerated api.md.

- Emit a warning event when an operator-managed PVC diverges from the desired
  spec (size/storageClassName/accessModes) instead of silently ignoring the drift,
  since the PVC is created once and not reconfigured in place. Added unit tests.

Co-authored-by: Copilot <[email protected]>
andrewsykim pushed a commit to kuberay-project/kuberay that referenced this pull request Jul 23, 2026
…ance (#5013)

* [GCS FT] Support embedded RocksDB storage backend for GCS fault tolerance

Add a second GCS fault tolerance backend to KubeRay: the embedded RocksDB
store introduced in ray-project/ray#63657, selected via
`gcsFaultToleranceOptions.backend: rocksdb`. Unlike Redis, RocksDB is linked
into the GCS process, so KubeRay only needs to provision a persistent volume,
mount it on the head Pod, and set a few env vars.

API:
- Add `Backend` discriminator (redis|rocksdb) and `GcsEmbeddedStorage`
  (existingClaim | size/storageClassName/accessModes, subPath) to
  `GcsFaultToleranceOptions`.
- Relax `RedisAddress` from required to optional; validation now enforces it
  for the redis backend (backward compatible, additive CRD change).

Controller:
- Split GCS FT pod wiring into redis/embedded helpers. The embedded path sets
  RAY_gcs_storage=rocksdb, RAY_gcs_storage_path=/data/gcs-state, and a stable
  RAY_CLUSTER_ID (RayCluster UID) marker, and mounts the PVC at /data/gcs-state.
- Add `reconcileGCSStoragePVC`: provisions `{cluster}-gcs-pvc` (GC'd via
  ownerReferences), no-ops for BYO `existingClaim`, and sets the PVC owner to
  the RayService when the RayCluster is service-owned so a zero-downtime
  upgrade does not discard GCS state.
- Add persistentvolumeclaims RBAC (kustomize + Helm chart, kept in sync).

Validation:
- Backend-aware rules: redis requires RedisAddress; rocksdb rejects redis-only
  fields, enforces existingClaim mutual-exclusion, and blocks user-set
  operator-managed env/mounts.

Tests and sample:
- Unit tests for pod wiring, validation, helpers, and the PVC reconciler
  (incl. RayService-owner handling).
- e2e tests in test/e2e: a non-gated wiring test that validates PVC lifecycle
  and head-Pod wiring against any Ray image, and a gated recovery test
  (KUBERAY_TEST_EMBEDDED_GCS_FT=true) that verifies real GCS state recovery
  across a head-Pod restart with a Ray image containing ray#63657.
- Sample `config/samples/ray-cluster.embedded-gcs-ft.yaml`.

Co-authored-by: Copilot <[email protected]>

* Address Bugbot review: embedded GCS FT deletion, PVC ownership, reserved volume

- Skip the Redis cleanup finalizer/Job for the embedded RocksDB backend. It only
  ran because the guard tested IsGCSFaultToleranceEnabled without checking the
  backend; embedded heads have no Redis, so the Job would stall CR deletion.
- Own the embedded GCS PVC by the RayCluster in all cases (drop the
  RayService-owner special case). Each RayCluster keys its own PVC by name and
  the stale-PVC marker is the RayCluster UID, so a PVC cannot be reused across
  clusters; the previous RayService ownership only orphaned PVCs across upgrades
  without reusing state. Cross-upgrade state persistence needs RWX/active-passive
  and remains out of scope.
- Reject a user-supplied head volume or volume mount named "gcs-storage" (in
  addition to the reserved /data/gcs-state mount path), preventing a duplicate
  volume name that would block head-Pod creation.

Add unit tests for all three.

Co-authored-by: Copilot <[email protected]>

* Address self-review: drop unused RAY_CLUSTER_ID, document RWX/upgrade persistence, warn on PVC drift

- Remove the RAY_CLUSTER_ID env var and its constant. The upstream Ray embedded
  RocksDB PR (ray-project/ray#63657) never reads RAY_CLUSTER_ID: RocksDbStoreClient
  takes cluster_id as a constructor arg passed empty in production, and
  ValidateOrWriteClusterIdMarker is a no-op when empty (cluster_id-based PVC
  fail-fast is explicitly deferred). Store identity/staleness is handled by Ray's
  persisted session_name marker, with no KubeRay input. The var was dead code and
  the accompanying comment misdescribed shipped Ray behavior.

- Document cross-upgrade persistence and single-writer expectations instead of
  restricting access modes. RocksDB is single-writer; users choose RWO (default,
  standalone RayCluster) or RWX (concurrent attach with externally-coordinated
  single writer). ExistingClaim is the supported path to persist GCS state across
  a RayService zero-downtime upgrade. Updated API field docs, controller comment,
  sample YAML, and regenerated api.md.

- Emit a warning event when an operator-managed PVC diverges from the desired
  spec (size/storageClassName/accessModes) instead of silently ignoring the drift,
  since the PVC is created once and not reconfigured in place. Added unit tests.

Co-authored-by: Copilot <[email protected]>

* Address PR review: remove stale Redis finalizer for embedded backend; document RayService-owned PVC deadlock

- Fix (Bugbot, medium): a RayCluster switched from the Redis backend to the
  embedded RocksDB backend still carries the Redis cleanup finalizer, but the
  main Redis-cleanup block is gated on !IsGCSFaultToleranceEmbedded, so the
  finalizer-removal path never ran and the CR could get stuck Terminating. Add an
  explicit deletion-time removal of the stale finalizer for embedded-backend
  clusters. Added Test_StaleRedisCleanupFinalizerRemovedForEmbeddedBackend.

- Document on reconcileGCSStoragePVC why an operator-managed PVC re-parented to
  the RayService does not enable automatic cross-upgrade persistence: RocksDB is a
  hard single-writer (enforced by its own LOCK file), and a zero-downtime
  (NewCluster) upgrade runs old+new clusters concurrently, so the new head cannot
  open the store (RWX) or attach the volume (RWO) until the old cluster is gone —
  deadlocking the upgrade. Safe operator-managed persistence needs an
  active-passive handoff (a different upgrade strategy), deferred as follow-up;
  ExistingClaim remains the supported cross-upgrade path.

Co-authored-by: Copilot <[email protected]>

* Regenerate applyconfiguration codegen for GcsEmbeddedStorage doc updates

The verify-codegen CI check failed because the doc-comment changes to
GcsEmbeddedStorage in raycluster_types.go were not propagated into the
generated applyconfiguration client (pkg/client/applyconfiguration/ray/v1/
gcsembeddedstorage.go). Ran hack/update-codegen.sh to regenerate.

Co-authored-by: Copilot <[email protected]>

* Address maintainer review: feature gate, retain-on-deletion, shorter mount path

Addresses andrewsykim's review on #5013:

- Add GCSFaultToleranceEmbeddedStorage alpha feature gate (Default: false),
  mirroring the alpha status of the Ray Core feature (ray#63657). The embedded
  RocksDB backend is now rejected by validation unless the gate is enabled.
  Enabled in the CI test-overrides overlay so e2e suites keep exercising it.

- Add GcsEmbeddedStorage.RetainOnClusterDeletion: when true, the operator-managed
  PVC keeps its data after the RayCluster is deleted (owner reference omitted /
  reconciled), so GCS state can be recovered by a new cluster via ExistingClaim.
  Default false preserves the existing GC-with-cluster behavior.

- Rename the embedded store mount path /data/gcs-state -> /data/gcs.

Regenerated applyconfiguration, CRDs, helm CRDs, and api docs. Added unit tests
for the feature gate and the retain behavior; full make test green.

Co-authored-by: Copilot <[email protected]>

* Re-trigger CI (flaky rayservice incremental-upgrade e2e)

The test-rayservice-incremental-upgrade-e2e-nightly-operator suite failed on
da58e80 while every other nightly-operator e2e suite (rayservice, rayservice-
suspend, raycluster-and-gcs, sample-yamls) passed, confirming the operator
deployed correctly. That suite exercises only the RayServiceIncrementalUpgrade
gate and Istio/Gateway-API traffic migration timing, none of which this PR
touches; it is green on master. Re-running to clear the flake.

Co-authored-by: Copilot <[email protected]>

* Address Bugbot: fix false storageClassName drift; reconcile PVC ownerRef on create race

- gcsStoragePVCDrift no longer reports drift when storageClassName is omitted
  (nil) in the spec: Kubernetes populates the live PVC with the resolved default
  StorageClass, so a nil-vs-default comparison was a false positive that emitted a
  recurring 'cannot be reconfigured in place' warning on every reconcile. Now only
  compare when the desired class is explicitly set.
- On the create path, if Create returns AlreadyExists (lost race after a NotFound
  Get), re-fetch the PVC and run reconcileGCSStoragePVCOwnerRef instead of
  returning early, so RetainOnClusterDeletion is still honored.

Added unit tests: no drift on omitted class w/ default-populated PVC; real drift
still flagged on an explicitly-set diverging class.

Co-authored-by: Copilot <[email protected]>

* Address review: rename existingClaim->claimName, deletionPolicy enum, drop redis RedisAddress requirement

Addresses andrewsykim review feedback on #5013:
- Rename GcsEmbeddedStorage.ExistingClaim -> ClaimName (claimName), matching
  k8s conventions (PersistentVolumeClaimVolumeSource.claimName); expand field
  docs to explain it is a user-provided existing claim.
- Replace RetainOnClusterDeletion bool with deletionPolicy enum
  (DeleteWithCluster | Retain, default DeleteWithCluster), which is more
  idiomatic (mirrors PV reclaimPolicy) and extensible.
- Drop the new 'RedisAddress is required when backend is redis' validation;
  master never enforced it and it may be supplied via env/annotations.

Regenerated codegen, CRDs, helm CRDs, and api-docs. Updated unit tests and
sample. Full make test green.

Co-authored-by: Copilot <[email protected]>

* Address rueian review: Owns(PVC), redis storage rejection, doc fixes

- SetupWithManager now Owns(&corev1.PersistentVolumeClaim{}) so deleted
  operator-managed GCS PVCs are recreated promptly instead of waiting for
  the periodic requeue.
- validateGcsFaultToleranceBackend now rejects Storage on the redis backend
  for symmetry with the rocksdb-only field rejections (+ unit test).
- Drop stale 'required / enforced by validation' wording from the
  RedisAddress field doc and regenerate api.md.
- Document the same-name recreate recovery path for deletionPolicy: Retain
  in the field docs and sample, and add a code comment on reconcileGCSStoragePVC
  explaining why erroring on an unowned existing PVC would break a Retain
  cluster's own steady-state reconcile.
- Soften the session_name parenthetical in the reconcileGCSStoragePVC doc.

Co-authored-by: Copilot <[email protected]>

* Address review: regenerate deepcopy for DeletionPolicy; make backend immutable

- Regenerate zz_generated.deepcopy.go so GcsEmbeddedStorage.DeepCopyInto
  deep-copies the DeletionPolicy pointer (was missing after the field was
  added). Fixes shared-allocation aliasing between copies (rueian, Cursor Bugbot).
- Add a kubebuilder XValidation immutability rule on
  gcsFaultToleranceOptions.backend (self == oldSelf), matching the existing
  managedBy precedent: switching the GCS backend on a live cluster would swap
  the whole store + head-Pod wiring and lose FT state. Regenerated CRDs
  (config + Helm) and api.md.

Co-authored-by: Copilot <[email protected]>

* Regenerate applyconfiguration for updated GCS FT field docs

update-codegen.sh had failed earlier on a sandbox permission error, leaving
the generated applyconfiguration comments stale relative to the source field
docs (RedisAddress wording, DeletionPolicy recovery note, Backend immutability
note). Regenerated so generated code matches the API types.

Co-authored-by: Copilot <[email protected]>

* Re-trigger CI (flaky test-rayjob-e2e-nightly-operator)

The rayjob e2e suite does not exercise any GCS FT code paths changed in this
PR, and it passed on the prior commit 4c575e7 (which contains all the runtime
changes); HEAD only adds doc comments to generated files. Re-running to clear
the flake.

Co-authored-by: Copilot <[email protected]>

* Fix golangci-lint: correct import grouping in gcs_ft_controller_unit_test.go

The gci formatter (via golangci-lint --fix in the pre-commit hook) regroups
the misplaced `ctrl "sigs.k8s.io/controller-runtime"` import with the other
sigs.k8s.io/controller-runtime imports. Applying the fix so the Lint
(pre-commit) check passes.

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>
rueian pushed a commit that referenced this pull request Jul 28, 2026
## Description

Adds user-facing documentation for the **alpha embedded RocksDB GCS
fault-tolerance backend** introduced in #63657. The RocksDB backend lets
the GCS
persist its state to a local RocksDB database on a persistent volume
instead of
requiring an external Redis instance, so there's no separate datastore
to run.

The KubeRay how-to targets the **native** integration merged in

[kuberay-project/kuberay#5013](kuberay-project/kuberay#5013),
which lets users opt in with `gcsFaultToleranceOptions.backend: rocksdb`
and has
the operator provision, mount, and garbage-collect the persistent
volume.

This is a **docs-only** PR (all changes map to the `doc` build tag). The
goal is
to make the feature discoverable within the existing Ray fault-tolerance
docs and
to collect early user feedback.

## What's included

- **`ray-core/fault_tolerance/gcs.rst`** — the canonical GCS
fault-tolerance page.
Introduces the two backends (external Redis vs. embedded RocksDB) up
front and
  adds an "Embedded RocksDB backend (alpha)" section covering:
- the recovery model (identical to Redis-backed FT; only the location of
state differs),
  - a Redis-vs-RocksDB comparison table (when to use which),
- how to enable it (`RAY_gcs_storage=rocksdb`, `RAY_gcs_storage_path`),
  - the single-writer constraint, and
- advanced tuning knobs (`RAY_gcs_rocksdb_io_pool_size`,
`RAY_gcs_rocksdb_strand_buckets`).
- **`cluster/kubernetes/user-guides/kuberay-gcs-rocksdb-ft.md`** — a new
step-by-step KubeRay how-to built on the native
`gcsFaultToleranceOptions.backend:
  rocksdb` API from kuberay#5013. It covers:
- opting in with `backend: rocksdb` (KubeRay provisions
`{cluster}-gcs-pvc`,
mounts it at `/data/gcs`, and sets `RAY_gcs_storage` /
`RAY_gcs_storage_path`
    automatically),
- enabling the alpha `GCSFaultToleranceEmbeddedStorage` operator feature
gate
    (off by default),
- the `storage` sub-fields (`size`, `storageClassName`, `accessModes`,
`subPath`,
    `deletionPolicy`, and `claimName` for a bring-your-own PVC),
- the operator-managed PVC lifecycle (`DeleteWithCluster` default vs.
`Retain`),
- the single-writer / `ReadWriteOnce` constraint and volume-throughput
sizing, and
  - recovery verification by deleting the head Pod.

KubeRay injects the worker `RAY_gcs_rpc_server_reconnect_timeout_s`
timeout
automatically (as with the Redis backend), so no manual env-var wiring
is needed.
  It's wired into the KubeRay user-guides toctree and list.
- **`kuberay-gcs-ft.md`** — cross-links the new RocksDB how-to from the
Redis page.

Content is authored to match the current docs organization:
concept/tuning lives
in `gcs.rst`, the practical Kubernetes walkthrough lives under the
KubeRay
user-guides, and the new page is discoverable via toctree, the guides
list, and a
`{seealso}` cross-reference.

## Related issues

- Related to #63657 (embedded RocksDB GCS backend, REP-64).
- KubeRay counterpart:
[kuberay-project/kuberay#5013](kuberay-project/kuberay#5013)
(merged), which adds native `gcsFaultToleranceOptions.backend: rocksdb`
support.

## Additional information

- New page authored as MyST Markdown (`.md`) per the docs authoring
rule; the only
`.rst` touched is the pre-existing `gcs.rst` (editing existing `.rst` is
allowed).
- The feature is branded as alpha (Ray's governed stability level)
throughout, with a feedback callout.
- The native KubeRay support isn't in a stable KubeRay release yet
(latest is v1.6.2),
so the how-to notes it requires KubeRay master/nightly, and it keeps the
`rayproject/ray:nightly` image because the Ray-side backend isn't in a
stable Ray
  release either.

## Checks

- [x] I've signed off every commit (`git commit -s`) to meet the DCO
requirement.
- [x] Docs-only change; verified all touched files map to the `doc` tag.
- [x] AI assistance was used to draft and revise these docs.

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
edoakes pushed a commit that referenced this pull request Jul 29, 2026
…bility (REP-64) (#64702)

## Why are these changes needed?

Follow-up to #63657 (embedded RocksDB GCS backend, REP-64) that fixes
the underlying pub/sub issue at its root and removes the temporary
"soft-durability" workaround.

### Root cause (proven in #64187)

GCS published the node-death notification from **inside** the node table
write's completion callback — *publish-after-persist*. Owners of
objects/tasks react to a node's death **only** from that single pushed
pub/sub notification (`core_worker.cc` `on_node_change`, DEAD branch),
and once subscribed there is no periodic owner-side re-poll. Gating the
publish on the durable write therefore couples cluster-wide death
detection to persist latency: under a slow backend (the RocksDB GCS with
per-write `fsync`) the notification is delayed enough to strand object
recovery and hang
`test_dynamic_generator_reconstruction_nondeterministic[None-*]` in
`list(gen)`.

The provenance PR #64187 demonstrates this deterministically on the
**in-memory GCS** (timing injected), confirming the bug is in Ray core
and backend-agnostic.

### Fix (F3 — publish node death before persist)

Publish node death on the in-memory `DEAD` transition, posted onto the
GCS `io_context` and **decoupled** from the durable write. Applied to
**both** node-death paths:
- `GcsNodeManager::InternalOnNodeFailure` — health-check failure.
- `GcsNodeManager::HandleUnregisterNode` — graceful unregistration.

Properties:
- Relaxes broadcast-after-durable ordering **only for the node
channel**. Safe because node death is a terminal, restart-re-derivable
transition (re-established by health checks on GCS restart).
- **Not** generalized to the actor channel. This is *not* because the
actor channel has extra client-side self-healing that nodes lack — in
fact the two are symmetric: both fetch current state on subscribe and
re-fetch on GCS restart (`AsyncResubscribe`), and neither periodically
re-polls an already-established subscription. The difference is
durability semantics: actor state is **not** terminal and can
legitimately change (e.g. `RESTARTING` → `ALIVE`) and must survive a GCS
crash in durable order, so its publish must stay gated on persist. Node
liveness is terminal and re-derivable, so relaxing the ordering is safe.
- Keeps strict durability; smallest change that removes the proven cause
at its source.

We deliberately did **not** add the optional owner-side fallback re-poll
(F5 in #64187): the demonstrated failure is a *slow* publish, not a
*dropped* one, and F5 would add a permanent periodic GCS poll to every
owner for a hypothetical the pub/sub layer already makes unlikely. It
remains an isolated future option if a genuinely dropped notification is
ever observed.

### Remove the soft-durability workaround

With the root cause fixed, all GCS tables use strict per-write WAL
`fsync` (`sync = true`) again. Deletes `SoftDurableTables()` and
simplifies `RocksDbStoreClient::SyncWriteOptions()` (now returns a
`const &` to a shared constant, no per-write copy). The `NODE`/`ACTOR`
relaxation is no longer needed.

## How do we know this is safe?

The ordering guarantee (death is broadcast before, and independently of,
the durable write) is covered end-to-end and at the unit level:

- **End-to-end regression** —
`test_dynamic_generator_reconstruction_nondeterministic[None-*]`
(`python/ray/tests/test_generators.py`) is the exact scenario the bug
hangs. It passes on the RocksDB GCS with strict fsync and no
soft-durability, i.e. purely because of F3.
- **Deterministic unit ordering tests** (`gcs_node_manager_test.cc`,
new):
- `TestNodeFailurePublishesDeathBeforePersist` — health-check path:
after `OnNodeFailure`, running exactly one queued handler broadcasts
DEAD while the persist-completion callback has **not** yet run.
- `TestUnregisterNodePublishesDeathBeforePersist` — graceful-unregister
path: the DEAD publish fires before the persist-completion callback
(which is what writes the DEAD export event).
Both fail against the old publish-after-persist behavior and pass with
F3, so they lock in the fix.
- **Provenance proof** (#64187) demonstrates the same lost-wakeup on the
in-memory GCS with injected timing, independent of any storage backend.

Practically-possible scenarios and why they remain safe: (a) slow
persist — publish is already decoupled; (b) GCS restart before persist —
node death is re-derived by health checks and clients re-fetch on
resubscribe; (c) dropped push (not observed) — out of scope for this PR
and independently addressable via the F5 backstop without touching F3.

## Related issue number

- Root-cause analysis / proof: #64187
- Introduced the workaround this PR removes: #63657

## Checks

- [x] `gcs_node_manager_test` (incl. new ordering tests),
`node_manager_export_event_test` pass
- [x] `rocksdb_store_client_test`, `rocksdb_smoke_test` pass
- [x] `gcs_server_lib` + `rocksdb_store_client` build cleanly
- [x] clang-format / black / ruff / pydoclint clean

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Rueian <[email protected]>
Artimislyy pushed a commit to Artimislyy/ray that referenced this pull request Aug 11, 2026
…bility (REP-64) (ray-project#64702)

## Why are these changes needed?

Follow-up to ray-project#63657 (embedded RocksDB GCS backend, REP-64) that fixes
the underlying pub/sub issue at its root and removes the temporary
"soft-durability" workaround.

### Root cause (proven in ray-project#64187)

GCS published the node-death notification from **inside** the node table
write's completion callback — *publish-after-persist*. Owners of
objects/tasks react to a node's death **only** from that single pushed
pub/sub notification (`core_worker.cc` `on_node_change`, DEAD branch),
and once subscribed there is no periodic owner-side re-poll. Gating the
publish on the durable write therefore couples cluster-wide death
detection to persist latency: under a slow backend (the RocksDB GCS with
per-write `fsync`) the notification is delayed enough to strand object
recovery and hang
`test_dynamic_generator_reconstruction_nondeterministic[None-*]` in
`list(gen)`.

The provenance PR ray-project#64187 demonstrates this deterministically on the
**in-memory GCS** (timing injected), confirming the bug is in Ray core
and backend-agnostic.

### Fix (F3 — publish node death before persist)

Publish node death on the in-memory `DEAD` transition, posted onto the
GCS `io_context` and **decoupled** from the durable write. Applied to
**both** node-death paths:
- `GcsNodeManager::InternalOnNodeFailure` — health-check failure.
- `GcsNodeManager::HandleUnregisterNode` — graceful unregistration.

Properties:
- Relaxes broadcast-after-durable ordering **only for the node
channel**. Safe because node death is a terminal, restart-re-derivable
transition (re-established by health checks on GCS restart).
- **Not** generalized to the actor channel. This is *not* because the
actor channel has extra client-side self-healing that nodes lack — in
fact the two are symmetric: both fetch current state on subscribe and
re-fetch on GCS restart (`AsyncResubscribe`), and neither periodically
re-polls an already-established subscription. The difference is
durability semantics: actor state is **not** terminal and can
legitimately change (e.g. `RESTARTING` → `ALIVE`) and must survive a GCS
crash in durable order, so its publish must stay gated on persist. Node
liveness is terminal and re-derivable, so relaxing the ordering is safe.
- Keeps strict durability; smallest change that removes the proven cause
at its source.

We deliberately did **not** add the optional owner-side fallback re-poll
(F5 in ray-project#64187): the demonstrated failure is a *slow* publish, not a
*dropped* one, and F5 would add a permanent periodic GCS poll to every
owner for a hypothetical the pub/sub layer already makes unlikely. It
remains an isolated future option if a genuinely dropped notification is
ever observed.

### Remove the soft-durability workaround

With the root cause fixed, all GCS tables use strict per-write WAL
`fsync` (`sync = true`) again. Deletes `SoftDurableTables()` and
simplifies `RocksDbStoreClient::SyncWriteOptions()` (now returns a
`const &` to a shared constant, no per-write copy). The `NODE`/`ACTOR`
relaxation is no longer needed.

## How do we know this is safe?

The ordering guarantee (death is broadcast before, and independently of,
the durable write) is covered end-to-end and at the unit level:

- **End-to-end regression** —
`test_dynamic_generator_reconstruction_nondeterministic[None-*]`
(`python/ray/tests/test_generators.py`) is the exact scenario the bug
hangs. It passes on the RocksDB GCS with strict fsync and no
soft-durability, i.e. purely because of F3.
- **Deterministic unit ordering tests** (`gcs_node_manager_test.cc`,
new):
- `TestNodeFailurePublishesDeathBeforePersist` — health-check path:
after `OnNodeFailure`, running exactly one queued handler broadcasts
DEAD while the persist-completion callback has **not** yet run.
- `TestUnregisterNodePublishesDeathBeforePersist` — graceful-unregister
path: the DEAD publish fires before the persist-completion callback
(which is what writes the DEAD export event).
Both fail against the old publish-after-persist behavior and pass with
F3, so they lock in the fix.
- **Provenance proof** (ray-project#64187) demonstrates the same lost-wakeup on the
in-memory GCS with injected timing, independent of any storage backend.

Practically-possible scenarios and why they remain safe: (a) slow
persist — publish is already decoupled; (b) GCS restart before persist —
node death is re-derived by health checks and clients re-fetch on
resubscribe; (c) dropped push (not observed) — out of scope for this PR
and independently addressable via the F5 backstop without touching F3.

## Related issue number

- Root-cause analysis / proof: ray-project#64187
- Introduced the workaround this PR removes: ray-project#63657

## Checks

- [x] `gcs_node_manager_test` (incl. new ordering tests),
`node_manager_export_event_test` pass
- [x] `rocksdb_store_client_test`, `rocksdb_smoke_test` pass
- [x] `gcs_server_lib` + `rocksdb_store_client` build cleanly
- [x] clang-format / black / ruff / pydoclint clean

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Rueian <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…nce (REP-64) (ray-project#63657)

Implements the embedded RocksDB storage backend for GCS fault tolerance
proposed in
[REP-64](ray-project/enhancements#64).

Today, GCS fault tolerance requires an external Redis instance. This PR
adds RocksDB as a second backend, selected via `RAY_gcs_storage=rocksdb`
and `RAY_gcs_storage_path=<path-on-pvc>`. The recovery model is
identical to Redis-backed FT — GCS restarts, reads state from local
disk, workers reconnect — only the location of persisted state differs.

KubeRay operator changes (the `gcsFaultToleranceOptions.backend:
rocksdb` field that auto-manages PVCs) are explicitly out of scope here
and will land in `ray-project/kuberay`.

## Why a new PR

This is a streamlined version of the POC at ray-project#63032. That PR carries the
full evidence dossier (phase reports, kill-9 harness, k8s test harness,
microbench results — ~10K lines of supporting material) which served its
purpose during design review. For the merge PR, only the production code
is included; ray-project#63032 remains the reference for per-claim reproducibility
evidence and the @andrewsykim review thread.

## What's in this PR

| Commit | What |
|---|---|
| 1 | `bazel/rocksdb.BUILD` + `bazel/ray_deps_setup.bzl` — add RocksDB
9.11.2 as a third-party dependency (static-only, no compression /
jemalloc / tools, built via `rules_foreign_cc`). |
| 2 | `src/ray/gcs/store_client/rocksdb_store_client.{h,cc}` + 4 tests +
`storage_microbench` binary. RocksDB I/O runs on a
`boost::asio::thread_pool` (keeping the WAL fsync off the GCS event
loop) with per-key `boost::asio::strand`s bucketed by `hash(table, key)`
for submission-order ordering. `WriteOptions::sync = true` on every
mutating call. |
| 3 | Wire it into `GcsServer` (factory dispatch in
`InitClusterStorageBackend` + `InitKVManager`, 3 new config flags,
`node.py` session-name sidecar for restart recovery, raylet startup wait
bumped 30 → 60s on rocksdb). |
| 4 | `TEST_GCS_ROCKSDB=1` fixture toggle in
`python/ray/tests/conftest.py` — existing cluster fixtures
auto-dispatch. |
| 5 | New postmerge buildkite jobs `:ray: core: rocksdb tests` + `:ray:
core: out of disk rocksdb tests`, mirroring the Redis FT jobs. |
| 6 | Docs: new K8s setup page (`kuberay-gcs-rocksdb-ft.md`) + an
"Embedded RocksDB backend" section in `gcs.rst`. |
| 7 | Review follow-ups: remove the inline execution path and the
`gcs_rocksdb_async_offload` toggle so RocksDB I/O always offloads; make
`GetNextJobIDSync` private (tests drive it through the public
`AsyncGetNextJobID`); extract the rocksdb session-name marker logic in
`node.py` into its own helper; collapse `storage_microbench` to a single
`rocksdb` backend; make the soft-durable table set a hardcoded,
documented constant (`SoftDurableTables()`) instead of the
`gcs_rocksdb_soft_durability_tables` config flag, since it's a fixed
design property rather than an operator knob. |

Aggregate: **+2,973 / -20 across 26 files**. All commits signed off
(DCO).

## REP-64 acceptance criteria

1. Release tests pass with `RAY_gcs_storage=rocksdb` — the new postmerge
job runs the standard test suite under the rocksdb backend.
2. New postmerge CI job mirroring Redis GCS FT — ✓ commit 5.
3. Scale tests at parity with Redis — covered by the postmerge job's
`//python/ray/tests/...` target set (includes `test_many_actors.py`).
4. Serve chaos passes — covered by the postmerge job.

## Tests

C++ unit tests under `src/ray/gcs/store_client/tests/`:
- `rocksdb_smoke_test` — Bazel-integration sanity (open / put / get).
- `rocksdb_store_client_test` — RocksDb-specific scenarios: recovery
across close+reopen, cluster-id marker fail-fast, pool-thread write
roundtrip.
- `rocksdb_parity_test` — runs the full `StoreClientTestBase` suite
(same fixture as `in_memory_store_client_test` and
`redis_store_client_test`).
- `rocksdb_concurrency_test` — per-key strand correctness +
JobID-counter atomicity under N-thread contention.

Python integration coverage: the existing `//python/ray/tests/...` /
`//python/ray/dag/...` / `//python/ray/autoscaler/v2/...` suites run
under `TEST_GCS_ROCKSDB=1` via the new buildkite jobs.

> The local k3d cluster recovery test harness from the POC branch was
repeated on this branch. Results and reproduction instructions are in
doc [REP-64 RocksDB GCS — Kubernetes Recovery: Evidence of Correctness &
Reproduction
Guide](https://docs.google.com/document/d/1sd6S1E5-kgOSbMjefjIkvkZztwsMeUikscOqbZHmUSA/edit?usp=sharing)

## Out of scope (follow-ons)

- KubeRay operator support for `gcsFaultToleranceOptions.backend:
rocksdb` — separate `ray-project/kuberay` PR.
- PVC stale-data fail-fast via K8s downward API (`RAY_CLUSTER_ID`
env-injected cluster-id marker) — `RocksDbStoreClient` already supports
the check; needs the KubeRay-side plumbing.
- Remove the soft-durability workaround. The soft-durability relaxation
added here (skipping the per-write WAL fsync on the NODE/ACTOR
death-notification tables, now a hardcoded `SoftDurableTables()`
constant) works around a GCS-core object-reconstruction /
task-resubmission race that RocksDB's fsync latency widens. That race
was proven to be rooted in the GCS code (see ray-project#64187). A follow-on PR
will fix the root cause in GCS and remove this workaround so every table
keeps strict per-write fsync.
- macOS / Windows support (targets currently gated on
`@platforms//os:linux`).

## References

- REP-64: ray-project/enhancements#64
- POC PR with full evidence dossier and design-review history: ray-project#63032
- Bug provenance: ray-project#64187

---------

Signed-off-by: Santosh Jha <[email protected]>
Signed-off-by: Rueian <[email protected]>
Signed-off-by: Edward Oakes <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Rueian <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Edward Oakes <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…nd (ray-project#64759)

## Why are these changes needed?

After ray-project#63657 merged, the C++ ThreadSanitizer (TSAN) build started
reporting data races in the embedded RocksDB GCS backend tests:

- `//src/ray/gcs/store_client/tests:rocksdb_store_client_test`
- `//src/ray/gcs/store_client/tests:rocksdb_concurrency_test`
- `//src/ray/gcs/store_client/tests:rocksdb_parity_test`

The reported races are **inside RocksDB itself**, e.g.:

```
WARNING: ThreadSanitizer: data race
  Write of size 2 by thread T180:
    #1 rocksdb::MemTable::Add(...)                       // memcpy of key bytes
  Previous read of size 2 by thread T182:
    #1 rocksdb::BytewiseComparatorImpl::Compare(...)     // memcmp during a Get
```

### Root cause

RocksDB is built as a static library by an **out-of-band CMake action**
(`bazel/rocksdb.BUILD` via `rules_foreign_cc`). Bazel's `--copt
-fsanitize=thread` and `--per_file_copt` from the `tsan` config only
apply to Bazel-compiled `cc_library` targets — they never reach the
CMake build. As a result, a TSAN-instrumented GCS test links an
**un-instrumented** `librocksdb.a`.

TSAN can intercept the plain `memcpy`/`memcmp` on the key/value bytes
inside RocksDB's lock-free memtable skiplist, but it **cannot see the
acquire/release atomics** RocksDB uses to publish and observe those
bytes (that synchronizing code is uninstrumented). Missing those
happens-before edges, TSAN reports false races.

Concurrent `Put`/`Get` across the store client's I/O offload pool is a
fully supported RocksDB operation, so these are false positives, not
real races. `report_atomic_races=0` (already set in the `tsan` config)
does not suppress them because the racing accesses are byte-wise
`memcpy`/`memcmp`, not atomic operations.

### Fix

Build RocksDB with its native `WITH_TSAN` CMake option under the `tsan`
config. RocksDB's `CMakeLists.txt` handles `WITH_TSAN` by adding
`-fsanitize=thread` to its own compile/link flags — the RocksDB-blessed
way to run it under TSAN. With RocksDB instrumented, ThreadSanitizer
understands its synchronization and the false positives disappear.

- `.bazelrc`: `--config=tsan` now sets `--define=ray_rocksdb_tsan=true`.
- `bazel/rocksdb.BUILD`: a `config_setting` reads that define and a
`cache_entries` `select()` flips `WITH_TSAN=ON` only for TSAN builds.

Non-TSAN builds are unaffected: the define is only set by
`--config=tsan`, and `WITH_TSAN` stays off in the default `select()`
branch. `--config=tsan-clang` inherits the define via `--config=tsan`.

### Verification

Reproduced and verified with the same toolchain CI uses
(`--config=tsan-clang`, clang 14, libc++). All three previously-failing
tests were built under TSAN and run (ASLR disabled via `setarch -R`,
`TSAN_OPTIONS=report_atomic_races=0`, matching CI):

| RocksDB build (clang-14 TSAN, identical otherwise) | Data races |
Result |
| --- | --- | --- |
| **Without this fix** (uninstrumented `librocksdb.a`) | **10** |
**FAILED** (TSAN exits 66) |
| **With this fix** (`WITH_TSAN=ON`) | **0** | **PASSED** |

The negative-control run (fix disabled via
`--define=ray_rocksdb_tsan=false`) reproduces the exact races from the
report — `rocksdb::MemTable::Add` (memcpy) racing
`rocksdb::BytewiseComparatorImpl::Compare` (memcmp) in the memtable
skiplist:

```
SUMMARY: ThreadSanitizer: data race in __interceptor_memcmp
  #1 rocksdb::(anonymous namespace)::BytewiseComparatorImpl::Compare(...) comparator.cc
  #1 rocksdb::MemTable::Add(...)
```

With the fix, the same runs are clean:

```
rocksdb_store_client_test   : 0 data races, [  PASSED  ] 12 tests
rocksdb_concurrency_test    : 0 data races, [  PASSED  ]  4 tests
rocksdb_parity_test         : 0 data races, [  PASSED  ]  2 tests
```

This confirms the fix both eliminates the reported races and that
removing it reproduces them — i.e. the instrumentation is the cause of
the change.

## Related issue number

Follow-up to ray-project#63657.

## Checks

- [x] I've signed off every commit (by using the -s flag, i.e., `git
commit -s`) in this PR.
- [x] I've made sure the tests are passing. Note that there might be a
few flaky tests, see the recent failures at https://flakey-tests.ray.io/
- Testing Strategy
   - [x] Unit tests
   - [ ] Release tests
   - [ ] This PR is not tested :(

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…core build) (ray-project#64748)

## Why

The aarch64 `wanda: core binary parts py3.{10..14}` postmerge jobs fail
intermittently with:

```
ERROR: .../rules_foreign_cc/toolchains/BUILD.bazel: BootstrapNinjaBuild ... failed
/bin/sh: c++: command not found
```

### Root cause

`bazel/rocksdb.BUILD` (added in ray-project#63657, embedded RocksDB GCS backend /
REP-64) builds RocksDB via `rules_foreign_cc`'s `cmake()` with
`generate_args = ["-G Ninja"]`. It's the repo's only foreign_cc target
using the Ninja generator. rules_foreign_cc 0.9.0 has no system ninja,
so it **bootstraps ninja from source**, invoking a bare `c++` under a
scrubbed `PATH=/bin:/usr/bin:/usr/local/bin`. The aarch64 manylinux2014
image has no `c++` on that PATH, so the bootstrap fails.

### Why it's intermittent

The failure only bites on a Bazel **remote-cache miss** for the ninja
tool. Full-suite (release-automation) postmerge history:

| build | commit | aarch64 core |
|-------|--------|--------------|
| 18544 | `914e1a06e1` (parent of ray-project#63657) | PASS |
| 18547 / 18549 / 18557 | — | FAIL |
| 18561 | `3ba205c1b0` | PASS (`5932 remote cache hit`, no bootstrap) |
| 18565 / 18567 | — | FAIL |

Cache hit → no bootstrap → pass; cache miss → compile ninja → `c++ not
found` → fail. This becomes a permanent failure once the cache entry is
evicted or invalidated by a config-hash change.

## What

Switch the RocksDB build from the Ninja generator to CMake's Unix
Makefiles generator. Make uses the preinstalled toolchain (as the
jemalloc/openssl foreign_cc builds already do) and needs no source
bootstrap, so the build is deterministic across cache states on every
architecture. Build output (`librocksdb.a`) is unchanged.

Only the ninja *tool bootstrap* was the problem — the RocksDB compile
itself uses Bazel's configured toolchain regardless of generator.

## Notes

- Not caused by, but surfaced alongside, the recent deps-unification
work; independent fix.
- cc the ray-project#63657 / REP-64 authors — this is your build rule. If keeping
Ninja is preferred, the alternative is pre-installing `ninja` in the
aarch64 manylinux image (heavier: image rebuild + `MANYLINUX_VERSION`
bump).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…4731)

## Description

Adds user-facing documentation for the **alpha embedded RocksDB GCS
fault-tolerance backend** introduced in ray-project#63657. The RocksDB backend lets
the GCS
persist its state to a local RocksDB database on a persistent volume
instead of
requiring an external Redis instance, so there's no separate datastore
to run.

The KubeRay how-to targets the **native** integration merged in

[kuberay-project/kuberay#5013](kuberay-project/kuberay#5013),
which lets users opt in with `gcsFaultToleranceOptions.backend: rocksdb`
and has
the operator provision, mount, and garbage-collect the persistent
volume.

This is a **docs-only** PR (all changes map to the `doc` build tag). The
goal is
to make the feature discoverable within the existing Ray fault-tolerance
docs and
to collect early user feedback.

## What's included

- **`ray-core/fault_tolerance/gcs.rst`** — the canonical GCS
fault-tolerance page.
Introduces the two backends (external Redis vs. embedded RocksDB) up
front and
  adds an "Embedded RocksDB backend (alpha)" section covering:
- the recovery model (identical to Redis-backed FT; only the location of
state differs),
  - a Redis-vs-RocksDB comparison table (when to use which),
- how to enable it (`RAY_gcs_storage=rocksdb`, `RAY_gcs_storage_path`),
  - the single-writer constraint, and
- advanced tuning knobs (`RAY_gcs_rocksdb_io_pool_size`,
`RAY_gcs_rocksdb_strand_buckets`).
- **`cluster/kubernetes/user-guides/kuberay-gcs-rocksdb-ft.md`** — a new
step-by-step KubeRay how-to built on the native
`gcsFaultToleranceOptions.backend:
  rocksdb` API from kuberay#5013. It covers:
- opting in with `backend: rocksdb` (KubeRay provisions
`{cluster}-gcs-pvc`,
mounts it at `/data/gcs`, and sets `RAY_gcs_storage` /
`RAY_gcs_storage_path`
    automatically),
- enabling the alpha `GCSFaultToleranceEmbeddedStorage` operator feature
gate
    (off by default),
- the `storage` sub-fields (`size`, `storageClassName`, `accessModes`,
`subPath`,
    `deletionPolicy`, and `claimName` for a bring-your-own PVC),
- the operator-managed PVC lifecycle (`DeleteWithCluster` default vs.
`Retain`),
- the single-writer / `ReadWriteOnce` constraint and volume-throughput
sizing, and
  - recovery verification by deleting the head Pod.

KubeRay injects the worker `RAY_gcs_rpc_server_reconnect_timeout_s`
timeout
automatically (as with the Redis backend), so no manual env-var wiring
is needed.
  It's wired into the KubeRay user-guides toctree and list.
- **`kuberay-gcs-ft.md`** — cross-links the new RocksDB how-to from the
Redis page.

Content is authored to match the current docs organization:
concept/tuning lives
in `gcs.rst`, the practical Kubernetes walkthrough lives under the
KubeRay
user-guides, and the new page is discoverable via toctree, the guides
list, and a
`{seealso}` cross-reference.

## Related issues

- Related to ray-project#63657 (embedded RocksDB GCS backend, REP-64).
- KubeRay counterpart:
[kuberay-project/kuberay#5013](kuberay-project/kuberay#5013)
(merged), which adds native `gcsFaultToleranceOptions.backend: rocksdb`
support.

## Additional information

- New page authored as MyST Markdown (`.md`) per the docs authoring
rule; the only
`.rst` touched is the pre-existing `gcs.rst` (editing existing `.rst` is
allowed).
- The feature is branded as alpha (Ray's governed stability level)
throughout, with a feedback callout.
- The native KubeRay support isn't in a stable KubeRay release yet
(latest is v1.6.2),
so the how-to notes it requires KubeRay master/nightly, and it keeps the
`rayproject/ray:nightly` image because the Ray-side backend isn't in a
stable Ray
  release either.

## Checks

- [x] I've signed off every commit (`git commit -s`) to meet the DCO
requirement.
- [x] Docs-only change; verified all touched files map to the `doc` tag.
- [x] AI assistance was used to draft and revise these docs.

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…bility (REP-64) (ray-project#64702)

## Why are these changes needed?

Follow-up to ray-project#63657 (embedded RocksDB GCS backend, REP-64) that fixes
the underlying pub/sub issue at its root and removes the temporary
"soft-durability" workaround.

### Root cause (proven in ray-project#64187)

GCS published the node-death notification from **inside** the node table
write's completion callback — *publish-after-persist*. Owners of
objects/tasks react to a node's death **only** from that single pushed
pub/sub notification (`core_worker.cc` `on_node_change`, DEAD branch),
and once subscribed there is no periodic owner-side re-poll. Gating the
publish on the durable write therefore couples cluster-wide death
detection to persist latency: under a slow backend (the RocksDB GCS with
per-write `fsync`) the notification is delayed enough to strand object
recovery and hang
`test_dynamic_generator_reconstruction_nondeterministic[None-*]` in
`list(gen)`.

The provenance PR ray-project#64187 demonstrates this deterministically on the
**in-memory GCS** (timing injected), confirming the bug is in Ray core
and backend-agnostic.

### Fix (F3 — publish node death before persist)

Publish node death on the in-memory `DEAD` transition, posted onto the
GCS `io_context` and **decoupled** from the durable write. Applied to
**both** node-death paths:
- `GcsNodeManager::InternalOnNodeFailure` — health-check failure.
- `GcsNodeManager::HandleUnregisterNode` — graceful unregistration.

Properties:
- Relaxes broadcast-after-durable ordering **only for the node
channel**. Safe because node death is a terminal, restart-re-derivable
transition (re-established by health checks on GCS restart).
- **Not** generalized to the actor channel. This is *not* because the
actor channel has extra client-side self-healing that nodes lack — in
fact the two are symmetric: both fetch current state on subscribe and
re-fetch on GCS restart (`AsyncResubscribe`), and neither periodically
re-polls an already-established subscription. The difference is
durability semantics: actor state is **not** terminal and can
legitimately change (e.g. `RESTARTING` → `ALIVE`) and must survive a GCS
crash in durable order, so its publish must stay gated on persist. Node
liveness is terminal and re-derivable, so relaxing the ordering is safe.
- Keeps strict durability; smallest change that removes the proven cause
at its source.

We deliberately did **not** add the optional owner-side fallback re-poll
(F5 in ray-project#64187): the demonstrated failure is a *slow* publish, not a
*dropped* one, and F5 would add a permanent periodic GCS poll to every
owner for a hypothetical the pub/sub layer already makes unlikely. It
remains an isolated future option if a genuinely dropped notification is
ever observed.

### Remove the soft-durability workaround

With the root cause fixed, all GCS tables use strict per-write WAL
`fsync` (`sync = true`) again. Deletes `SoftDurableTables()` and
simplifies `RocksDbStoreClient::SyncWriteOptions()` (now returns a
`const &` to a shared constant, no per-write copy). The `NODE`/`ACTOR`
relaxation is no longer needed.

## How do we know this is safe?

The ordering guarantee (death is broadcast before, and independently of,
the durable write) is covered end-to-end and at the unit level:

- **End-to-end regression** —
`test_dynamic_generator_reconstruction_nondeterministic[None-*]`
(`python/ray/tests/test_generators.py`) is the exact scenario the bug
hangs. It passes on the RocksDB GCS with strict fsync and no
soft-durability, i.e. purely because of F3.
- **Deterministic unit ordering tests** (`gcs_node_manager_test.cc`,
new):
- `TestNodeFailurePublishesDeathBeforePersist` — health-check path:
after `OnNodeFailure`, running exactly one queued handler broadcasts
DEAD while the persist-completion callback has **not** yet run.
- `TestUnregisterNodePublishesDeathBeforePersist` — graceful-unregister
path: the DEAD publish fires before the persist-completion callback
(which is what writes the DEAD export event).
Both fail against the old publish-after-persist behavior and pass with
F3, so they lock in the fix.
- **Provenance proof** (ray-project#64187) demonstrates the same lost-wakeup on the
in-memory GCS with injected timing, independent of any storage backend.

Practically-possible scenarios and why they remain safe: (a) slow
persist — publish is already decoupled; (b) GCS restart before persist —
node death is re-derived by health checks and clients re-fetch on
resubscribe; (c) dropped push (not observed) — out of scope for this PR
and independently addressable via the F5 backstop without touching F3.

## Related issue number

- Root-cause analysis / proof: ray-project#64187
- Introduced the workaround this PR removes: ray-project#63657

## Checks

- [x] `gcs_node_manager_test` (incl. new ordering tests),
`node_manager_export_event_test` pass
- [x] `rocksdb_store_client_test`, `rocksdb_smoke_test` pass
- [x] `gcs_server_lib` + `rocksdb_store_client` build cleanly
- [x] clang-format / black / ruff / pydoclint clean

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Rueian <[email protected]>
Signed-off-by: 400Ping <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…bility (REP-64) (ray-project#64702)

## Why are these changes needed?

Follow-up to ray-project#63657 (embedded RocksDB GCS backend, REP-64) that fixes
the underlying pub/sub issue at its root and removes the temporary
"soft-durability" workaround.

### Root cause (proven in ray-project#64187)

GCS published the node-death notification from **inside** the node table
write's completion callback — *publish-after-persist*. Owners of
objects/tasks react to a node's death **only** from that single pushed
pub/sub notification (`core_worker.cc` `on_node_change`, DEAD branch),
and once subscribed there is no periodic owner-side re-poll. Gating the
publish on the durable write therefore couples cluster-wide death
detection to persist latency: under a slow backend (the RocksDB GCS with
per-write `fsync`) the notification is delayed enough to strand object
recovery and hang
`test_dynamic_generator_reconstruction_nondeterministic[None-*]` in
`list(gen)`.

The provenance PR ray-project#64187 demonstrates this deterministically on the
**in-memory GCS** (timing injected), confirming the bug is in Ray core
and backend-agnostic.

### Fix (F3 — publish node death before persist)

Publish node death on the in-memory `DEAD` transition, posted onto the
GCS `io_context` and **decoupled** from the durable write. Applied to
**both** node-death paths:
- `GcsNodeManager::InternalOnNodeFailure` — health-check failure.
- `GcsNodeManager::HandleUnregisterNode` — graceful unregistration.

Properties:
- Relaxes broadcast-after-durable ordering **only for the node
channel**. Safe because node death is a terminal, restart-re-derivable
transition (re-established by health checks on GCS restart).
- **Not** generalized to the actor channel. This is *not* because the
actor channel has extra client-side self-healing that nodes lack — in
fact the two are symmetric: both fetch current state on subscribe and
re-fetch on GCS restart (`AsyncResubscribe`), and neither periodically
re-polls an already-established subscription. The difference is
durability semantics: actor state is **not** terminal and can
legitimately change (e.g. `RESTARTING` → `ALIVE`) and must survive a GCS
crash in durable order, so its publish must stay gated on persist. Node
liveness is terminal and re-derivable, so relaxing the ordering is safe.
- Keeps strict durability; smallest change that removes the proven cause
at its source.

We deliberately did **not** add the optional owner-side fallback re-poll
(F5 in ray-project#64187): the demonstrated failure is a *slow* publish, not a
*dropped* one, and F5 would add a permanent periodic GCS poll to every
owner for a hypothetical the pub/sub layer already makes unlikely. It
remains an isolated future option if a genuinely dropped notification is
ever observed.

### Remove the soft-durability workaround

With the root cause fixed, all GCS tables use strict per-write WAL
`fsync` (`sync = true`) again. Deletes `SoftDurableTables()` and
simplifies `RocksDbStoreClient::SyncWriteOptions()` (now returns a
`const &` to a shared constant, no per-write copy). The `NODE`/`ACTOR`
relaxation is no longer needed.

## How do we know this is safe?

The ordering guarantee (death is broadcast before, and independently of,
the durable write) is covered end-to-end and at the unit level:

- **End-to-end regression** —
`test_dynamic_generator_reconstruction_nondeterministic[None-*]`
(`python/ray/tests/test_generators.py`) is the exact scenario the bug
hangs. It passes on the RocksDB GCS with strict fsync and no
soft-durability, i.e. purely because of F3.
- **Deterministic unit ordering tests** (`gcs_node_manager_test.cc`,
new):
- `TestNodeFailurePublishesDeathBeforePersist` — health-check path:
after `OnNodeFailure`, running exactly one queued handler broadcasts
DEAD while the persist-completion callback has **not** yet run.
- `TestUnregisterNodePublishesDeathBeforePersist` — graceful-unregister
path: the DEAD publish fires before the persist-completion callback
(which is what writes the DEAD export event).
Both fail against the old publish-after-persist behavior and pass with
F3, so they lock in the fix.
- **Provenance proof** (ray-project#64187) demonstrates the same lost-wakeup on the
in-memory GCS with injected timing, independent of any storage backend.

Practically-possible scenarios and why they remain safe: (a) slow
persist — publish is already decoupled; (b) GCS restart before persist —
node death is re-derived by health checks and clients re-fetch on
resubscribe; (c) dropped push (not observed) — out of scope for this PR
and independently addressable via the F5 backstop without touching F3.

## Related issue number

- Root-cause analysis / proof: ray-project#64187
- Introduced the workaround this PR removes: ray-project#63657

## Checks

- [x] `gcs_node_manager_test` (incl. new ordering tests),
`node_manager_export_event_test` pass
- [x] `rocksdb_store_client_test`, `rocksdb_smoke_test` pass
- [x] `gcs_server_lib` + `rocksdb_store_client` build cleanly
- [x] clang-format / black / ruff / pydoclint clean

---------

Signed-off-by: Santosh Jha <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Rueian <[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 docs An issue or change related to documentation go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants