Repository navigation
[core] move high-volume metric recording to a separate I/O context - #66847
sca-anyscale wants to merge 11 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request decouples metric recording from the main event loops of various Ray components (such as the Core Worker, GCS Server, Raylet, and Object Manager) by routing metric updates asynchronously to a dedicated metric_context running on a separate thread. Feedback on these changes highlights a critical use-after-free bug in event_stats.cc due to capturing a parameter by reference in an asynchronous lambda. Additionally, the reviewer suggests passing the metric context as a pointer rather than a reference to avoid allocating heavy dummy io_context instances when metrics are disabled, removing redundant parameters in ServerCall methods, deleting an unused metric_thread_ member in GcsServer, and ensuring that spawned metric threads are safely joined on all exit paths in main functions to prevent crashes.
| virtual void HandleRequest(boost::asio::io_context &metric_context) = 0; | ||
|
|
||
| /// Invoked when sending reply successes. | ||
| virtual void OnReplySent() = 0; | ||
| virtual void OnReplySent(boost::asio::io_context &metric_context) = 0; | ||
|
|
||
| // Invoked when sending reply fails. | ||
| virtual void OnReplyFailed() = 0; | ||
| virtual void OnReplyFailed(boost::asio::io_context &metric_context) = 0; |
There was a problem hiding this comment.
Passing metric_context as a parameter to HandleRequest, OnReplySent, and OnReplyFailed is redundant. ServerCallImpl already receives metric_context in its constructor and stores it as a member variable metric_context_ (line 496).
In fact, the implementations of OnReplySent, OnReplyFailed, and LogProcessTime already use the member variable metric_context_ instead of the passed parameter, and HandleRequest does not use the parameter at all. Removing this parameter from these virtual functions and their callers (like GrpcServer::PollEventsFromCompletionQueue) will significantly clean up the gRPC server infrastructure changes.
virtual void HandleRequest() = 0;
/// Invoked when sending reply successes.
virtual void OnReplySent() = 0;
// Invoked when sending reply fails.
virtual void OnReplyFailed() = 0;| EventTracker(boost::asio::io_context &metric_context) | ||
| : global_stats_(std::make_shared<GuardedGlobalStats>()), | ||
| metric_context_(metric_context) {} |
There was a problem hiding this comment.
Instead of taking boost::asio::io_context & by reference, consider taking it as a pointer boost::asio::io_context *metric_context = nullptr.
This allows us to avoid constructing heavy dummy boost::asio::io_context instances (like unused_metric_context_ in instrumented_io_context and unused_io_context_ in InstrumentedIOContextWithThread) just to satisfy reference parameters when metrics are disabled. If the pointer is null, we can simply skip posting to it.
| EventTracker(boost::asio::io_context &metric_context) | |
| : global_stats_(std::make_shared<GuardedGlobalStats>()), | |
| metric_context_(metric_context) {} | |
| EventTracker(boost::asio::io_context *metric_context = nullptr) | |
| : global_stats_(std::make_shared<GuardedGlobalStats>()), | |
| metric_context_(metric_context) {} |
| boost::asio::io_context &metric_context_; | ||
| }; |
| std::shared_ptr<EventTracker> event_stats_; | ||
| bool emit_metrics_; | ||
| std::optional<std::string> context_name_; | ||
| boost::asio::io_context unused_metric_context_; | ||
| }; |
There was a problem hiding this comment.
With EventTracker taking a pointer to boost::asio::io_context, we can completely remove the unused_metric_context_ member variable. This avoids allocating and constructing a heavy boost::asio::io_context for every instrumented_io_context instance where metrics are disabled.
std::shared_ptr<EventTracker> event_stats_;
bool emit_metrics_;
std::optional<std::string> context_name_;
};| std::thread io_thread_; | ||
| std::string thread_name_; | ||
| bool used_for_health_check_; | ||
| boost::asio::io_context unused_io_context_; | ||
| }; |
| metric_context_.get_executor()); | ||
| SetThreadName("metric_recorder"); | ||
| metric_context_.run(); | ||
| }))) { |
There was a problem hiding this comment.
Constructor failure hangs metric thread
Medium Severity
The metric recorder thread is now started in the initializer list and kept alive by a work guard. If the constructor body later throws, CoreWorkerProcessImpl's destructor does not run, so metric_context_.stop() never happens. JoinableThread then join()s a thread blocked in io_context::run(), hanging worker startup instead of exiting.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 3ec6790. Configure here.
3ec6790 to
20307a1
Compare
20307a1 to
557a967
Compare
…ncy metrics (#65583) ## Description `gcs_storage_operation_count` and `gcs_storage_operation_latency_ms` are labeled by `Operation` only, so a slow `GetAll` on the actor table can't be told apart from one on the job table without correlating logs. `ObservableStoreClient` already receives a `table_name` on every call. This PR: - records it as a bounded `TableName` label on both metrics, for `Put`, `Get`, `GetAll`, `MultiGet`, `Delete`, `BatchDelete`, `GetKeys` and `Exists`; - instruments `GetNextJobID`, the one storage operation the wrapper used to skip; - measures latency on the monotonic clock instead of wall time; - documents both metrics in `system-metrics.md`. Exporting these metrics on the external-Redis backend, where they don't exist today, was split out of this PR at review into #66882. ## Related issues Closes #65582. ## Additional information ### Label cardinality `StoreClient` accepts any string as a table name (the shared test base passes `"test_table"`), so the label is bounded explicitly: `NormalizeTableNameLabel` keeps names from the `rpc::TablePrefix` enum and maps anything else to `OTHER`. In practice the GCS produces seven values: `JOB`, `ACTOR`, `ACTOR_TASK_SPEC`, `PLACEMENT_GROUP`, `NODE`, `WORKERS` and `KV`. The hard upper bound is 161 `Operation` × `TableName` combinations per GCS process (8 table operations × 20 values, plus `GetNextJobID` × `JobCounter`), independent of cluster size or actor count. No user-controlled string reaches a label: the internal KV puts the user's namespace in the key (`MakeKey` in `store_client_kv.cc`), not in the table name. `NoUserDataInLabels` covers this. ### `GetNextJobID` It addresses a counter key rather than a table, so it reports the `JobCounter` sentinel. It can't simply leave `TableName` unset: `tag_keys` is the tag allowlist on both metric stacks, and a declared tag that a call site doesn't record is exported as an empty string, so it would show up as `TableName=""`. ### Latency clock Latency used to be the difference of two `NowUnixNanos()` readings, which is wall time, so an NTP step could record a negative or inflated value. Every recording site is rewritten here anyway, so they now use `SteadyNow()`, which `ClockInterface` documents as the clock for durations. ### Compatibility / release note This changes series identity: each `Operation` now has up to seven series instead of one, and `GetNextJobID` is a new `Operation` value. Label matchers are unaffected. A dashboard or alert that assumed one series per operation can aggregate the new label away: ```promql sum without (TableName) (rate(ray_gcs_storage_operation_count_total[5m])) ``` Use `without (TableName)` rather than `by (Operation)`, because `by` also drops `SessionName`, `Component` and the other global labels. Aggregations sensitive to series count (`avg`, `max`, `count`) still change. ### Not a duplicate Searching open PRs for `"TableName gcs_storage_operation"`, `"observable store client"`, `"gcs_storage_operation redis"` and `"MaybeObserve"` finds no other PR labeling these metrics. #66847 edits the same `Record` call sites to move recording onto a separate io_context. It changes where recording runs, not what is recorded, so the two compose and whichever lands second rebases. ### Testing ```bash bazel test //src/ray/gcs/store_client/tests:table_name_label_test \ //src/ray/gcs/store_client/tests:observable_store_client_test \ //src/ray/gcs/store_client/tests:in_memory_store_client_test # Executed 3 out of 3 tests: 3 tests pass. pre-commit run --from-ref upstream/master --to-ref HEAD # All hooks passed. ``` AI assistance (Claude Code) was used to prepare this change. I reviewed every changed line and ran the tests above locally. --------- Signed-off-by: zzchun <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Douglas Strodtman <[email protected]>
557a967 to
1f84e10
Compare
| boost::asio::post(metric_context_, [this, start, table]() { | ||
| storage_operation_latency_in_ms_histogram_.Record( | ||
| ElapsedMs(clock_, start), MetricTags("Put", table)); | ||
| }); |
There was a problem hiding this comment.
Store latency includes metric queue delay
Medium Severity
ElapsedMs for storage operations now runs inside the posted metric task instead of when the operation finishes. Recorded GCS storage latency therefore includes however long the sample sat on metric_context_, which grows under the high-volume load this change is meant to handle.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 1f84e10. Configure here.
db281b1 to
444af27
Compare
…#66882) ## Description `gcs_storage_operation_count` and `gcs_storage_operation_latency_ms` are exported by the in-memory and RocksDB GCS storage backends, but not at all on the external-Redis backend: `RedisStoreClient` is the only `StoreClient` that `GcsServer` never wraps in `ObservableStoreClient`. Dashboards built on these metrics therefore go blank on Redis-backed clusters. This PR routes both `REDIS_PERSIST` construction sites in `GcsServer` (cluster tables and internal KV) through a small `gcs::MaybeObserve` helper, gated by a new `gcs_redis_storage_metrics_enabled` config (default `true`). ## Related issues Split out of #65583 at review. That PR adds a `TableName` label to the same two metrics; this one makes them exist on Redis. The two are independent and can land in either order. ## Additional information ### Kill switch Redis is the one backend that gains `Record` calls where it had none, so it gets a rollback switch: `RAY_gcs_redis_storage_metrics_enabled=false` restores the previous behavior. The in-memory and RocksDB backends have always been wrapped and are not gated. ### Ownership `ObservableStoreClient` now takes its delegate as a `shared_ptr` instead of a `unique_ptr`. `AsyncCheckHealth` is declared on `RedisStoreClient` and not on the `StoreClient` interface, so `GcsServer` keeps a concrete pointer for the periodic health check while handing the same client to the wrapper. `StoreClientInternalKV` takes a `shared_ptr` too, because it now consumes `MaybeObserve`'s result. Existing construction sites pass `unique_ptr` rvalues, which convert implicitly, so none of them change. Health-check `PING`s keep bypassing the wrapper: a probe is not a storage operation and should not appear in `gcs_storage_operation_count`. ### Compatibility Purely additive: on Redis, series that did not exist begin to exist. No existing series on any backend changes. ### Not a duplicate This is the Redis half of #65583, split out at the reviewer's request; #65583 no longer contains it. Searching open PRs for `"observable store client"`, `"gcs_storage_operation redis"` and `"MaybeObserve"` finds no other PR doing this. #66847 adds a `metric_context` parameter to the `ObservableStoreClient` constructor; whichever lands second threads it through `MaybeObserve`. ### Testing ```bash bazel test //src/ray/gcs/store_client/tests:observable_store_client_test \ //src/ray/gcs/store_client/tests:in_memory_store_client_test \ //src/ray/gcs/tests:redis_gcs_table_storage_test \ //src/ray/gcs/tests:gcs_kv_manager_test \ //src/ray/gcs/tests:gcs_server_rpc_test \ //src/ray/gcs:gcs_server # Executed 5 out of 5 tests: 5 tests pass; gcs_server builds. # New cases: MaybeObserveTest.{RecordsWhenEnabled,RecordsNothingWhenDisabled}, # RedisObservableGcsTableStorageTest.{RecordsOnTheRedisBackend, # RecordsNothingWhenTheKillSwitchIsOff} (against a real redis-server). pre-commit run --from-ref upstream/master --to-ref HEAD # All hooks passed. ``` The new tests match on the `Operation` tag only, so they keep passing whether or not #65583's `TableName` label lands first. --------- Signed-off-by: zzchun <[email protected]>
444af27 to
d334aa9
Compare
d334aa9 to
9c4ea71
Compare
- this creates a new Boost ASIO context in the raylet, GCS, and the core worker - instrumented_io_context now supports a metric context to use for recording metrics - high-usage metric users have been modified to post their recording to the new context. This currently includes: - gRPC server contexts, - the instrumented store client - the event tracker - some tests have been modified to account for these changes; many tests can still use the 3-argument constructor for instrumented I/O contexts if the test does not need metrics to be recorded Signed-off-by: Steve Alexander <[email protected]>
Signed-off-by: Steve Alexander <[email protected]>
Signed-off-by: Steve Alexander <[email protected]>
Signed-off-by: Steve Alexander <[email protected]>
Signed-off-by: Steve Alexander <[email protected]>
- move metric_context.stop() as suggested by the review bot Signed-off-by: Steve Alexander <[email protected]>
- this requires initializing it in the constructor since there is no default constructor - move metric_context.stop() before stats::Shutdown() Signed-off-by: Steve Alexander <[email protected]>
Signed-off-by: Steve Alexander <[email protected]>
Signed-off-by: Steve Alexander <[email protected]>
Signed-off-by: Steve Alexander <[email protected]>
Signed-off-by: Steve Alexander <[email protected]>
9c4ea71 to
d6fe172
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 3 total unresolved issues (including 2 from previous reviews).
Reviewed by Cursor Bugbot for commit d6fe172. Configure here.
| if (thread_.joinable()) { | ||
| thread_.join(); | ||
| } | ||
| } |
There was a problem hiding this comment.
Metric thread hang on exception
High Severity
JoinableThread always join()s, but the recorder thread stays in io_context::run() under an executor_work_guard until someone calls stop(). If CoreWorkerProcessImpl construction throws after metric_thread_ starts, or GCS/raylet startup fails after the thread is created, the destructor joins a thread that never exits and the process hangs.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit d6fe172. Configure here.
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |


Overview
GCS can incur significant overhead when metric collection (primarily Open Telemetry) is enabled. Although the profiling data is fuzzy, there seems to be lock contention on the mutex used by OpenTelemetryMetricRecorder::SetMetricValue().
This overhead seems to become significant as the number of nodes in a Ray cluster increases. Somewhere between 4000 and 9000 nodes this results in high overhead in the following GCS threads:
The overhead in the KV thread seems to be made worse by the dashboard. An idle cluster with 9996 nodes produces millions of get requests for the ‘dashboard’ key in the ‘dashboard’ namespace. This could be due to the retry interval used by the dashboard code being too small for this load, but that has not been confirmed definitively yet.
The net result is that at high load on a large cluster, between 15% and 40% of the CPU cycles measured in profiling of the gcs_server thread are being spent in Metric::Record(), depending on the workload and the cluster size.
Proposed Solution
Moving the invocation of Metric::Record() to a separate Boost ASIO context seems to work well. This has been tested with the following components:
These components have been modified to defer execution of Metric::Record() to a new context, called ‘metric_recorder’. This affects GCS, the raylet, and the core worker, as all three use the same instrumented I/O context and gRPC server infrastructure. The storage client is currently used only by GCS.
Sample Results
Details
Event Tracker
When an EventTracker is created, it now requires an ASIO context reference as an argument. Calls to Metric::Record() will be posted to this context.
Instrumented I/O Context
One issue here is that a new four-argument constructor has been added. The 3-argument constructor delegates to this, passing an unused context argument. This was done in order to avoid modifying a large number of test classes that create instrumented contexts. Some test cases that passed a single string argument were modified to initialize ‘emit_metrics’ and ‘running_on_single_thread’ correctly, as the string seems to be interpreted as a boolean ‘true’ value.
gRPC Server Infrastructure
This got a little messy. The lifetime of a ServerCall is much shorter than the lifetime of the shared statistics so a reference to the metrics is passed during the post operation, along with a copy of the call name.
Initializing a server call factory now supplies the context so that the metrics can be recorded using it.
Observable Store Client
Creating a storage client now requires a context reference. Metric recording will be posted to this context.
GCS Server
Gcs_server_main creates the metric context and hands a reference to it to the classes that need it. It also stops the context and joins the thread when exiting.
The context is passed to all server call factories.
Raylet
main() creates the metric context and hands a reference to it to the classes that need it. It also stops the context and joins the thread when exiting.
The context is passed to the node manager and the object manager for use when initializing their gRPC servers.
Core Worker
The metric context and thread are created in the CoreWorkerProcessImpl constructor, and cleaned up in its destructor. The context is supplied to the GrpcServer in CreateCoreWorker().