Skip to content

[core] move high-volume metric recording to a separate I/O context - #66847

Open
sca-anyscale wants to merge 11 commits into
ray-project:masterfrom
sca-anyscale:sca/metric-context-1
Open

sca-anyscale wants to merge 11 commits into
ray-project:masterfrom
sca-anyscale:sca/metric-context-1

Conversation

@sca-anyscale

Copy link
Copy Markdown

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:

  • gcs_server
  • internal_kv_io_
  • resource_load_puller

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:

  • EventTracker
  • ServerCallImpl
  • ObservableStoreClient

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

Benchmark Original Results With Metric Context Notes
64000 actors, 4000 nodes, node affinity scheduling 113s 81s Base: Mainline as of 4ca25fd

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().

@sca-anyscale
sca-anyscale requested a review from a team as a code owner October 8, 2026 17:36

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

Comment thread src/ray/common/event_stats.cc Resolved
Comment thread src/ray/rpc/server_call.h Outdated
Comment on lines +117 to +123
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;

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.

high

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;

Comment on lines +111 to +113
EventTracker(boost::asio::io_context &metric_context)
: global_stats_(std::make_shared<GuardedGlobalStats>()),
metric_context_(metric_context) {}

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.

high

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.

Suggested change
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) {}

Comment on lines +206 to 207
boost::asio::io_context &metric_context_;
};

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.

high

Change this to a pointer to support optional/null metric contexts without needing dummy io_context member variables.

Suggested change
boost::asio::io_context &metric_context_;
};
boost::asio::io_context *metric_context_;
};

Comment on lines 72 to 76
std::shared_ptr<EventTracker> event_stats_;
bool emit_metrics_;
std::optional<std::string> context_name_;
boost::asio::io_context unused_metric_context_;
};

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.

high

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_;
};

Comment thread src/ray/asio/asio_util.h
Comment on lines 111 to 115
std::thread io_thread_;
std::string thread_name_;
bool used_for_health_check_;
boost::asio::io_context unused_io_context_;
};

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.

high

Similarly, we can remove unused_io_context_ from InstrumentedIOContextWithThread by passing nullptr to the delegated constructor when no metric context is provided.

  std::thread io_thread_;
  std::string thread_name_;
  bool used_for_health_check_;
};

Comment thread src/ray/gcs/gcs_server.h Resolved
Comment thread src/ray/gcs/gcs_server_main.cc Resolved
Comment thread src/ray/raylet/main.cc Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread src/ray/raylet/main.cc Resolved
Comment thread src/ray/gcs/gcs_server_main.cc Resolved
Comment thread src/ray/asio/instrumented_io_context.h Resolved
@ray-gardener ray-gardener Bot added the core Issues that should be addressed in Ray Core label Oct 8, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

metric_context_.get_executor());
SetThreadName("metric_recorder");
metric_context_.run();
}))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3ec6790. Configure here.

Comment thread src/ray/util/joinable_thread.h Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread src/ray/asio/asio_util.h Resolved
rueian pushed a commit that referenced this pull request Oct 13, 2026
…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]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

boost::asio::post(metric_context_, [this, start, table]() {
storage_operation_latency_in_ms_histogram_.Record(
ElapsedMs(clock_, start), MetricTags("Put", table));
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 1f84e10. Configure here.

Comment thread src/ray/util/joinable_thread.h Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread src/ray/common/event_stats.h Resolved
rueian pushed a commit that referenced this pull request Oct 19, 2026
…#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]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread src/ray/util/joinable_thread.h Resolved
- 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]>
- 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]>

@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 and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit d6fe172. Configure here.

if (thread_.joinable()) {
thread_.join();
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d6fe172. Configure here.

@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

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.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 17, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Issues that should be addressed in Ray Core stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant