Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request adds support for collecting Prometheus metrics for autoscaling decisions in Ray Serve. The changes include updates to the configuration and protobuf definitions, and new logic in the replica to fetch metrics from a Prometheus endpoint. While the feature is a valuable addition, I've found a few critical issues in the implementation. The logic for fetching metrics is incorrect for labeled metrics (like histograms), which will lead to unexpected behavior. There's also a potential TypeError if Prometheus metrics are not configured. Additionally, the tests for this new feature could be strengthened to catch these kinds of issues. My review includes specific suggestions to address these points.
| def check_autoscaling_metrics_include_prometheus( | ||
| client, deployment_id: DeploymentID, expected_metrics: List[str] | ||
| ) -> bool: | ||
| """Check that autoscaling metrics include the expected prometheus metrics.""" | ||
|
|
||
| try: | ||
| metrics = get_autoscaling_metrics_from_controller(client, deployment_id) | ||
| # The metrics should include both ongoing requests and prometheus custom metrics | ||
| if not metrics: | ||
| print("No metrics returned from controller!") | ||
| return False | ||
|
|
||
| # For prometheus custom metrics, we expect the keys to be present in the dict | ||
| for expected_metric in expected_metrics: | ||
| if expected_metric not in metrics: | ||
| print(f"Expected metric {expected_metric} not found") | ||
| return False | ||
| return True | ||
| except Exception as e: | ||
| print(f"Error checking metrics: {e}") | ||
| return False |
There was a problem hiding this comment.
The test helper check_autoscaling_metrics_include_prometheus and the associated tests are not strong enough. They only check for the presence of the metric key in the results, not the correctness of its value. Because the implementation falls back to 0.0 on any error (including metric not found), the tests will pass even if the metric fetching logic is broken.
To make the tests more robust, they should be updated to:
- Use a simple, predictable metric for testing (e.g., a gauge that you can set manually).
- Assert that the fetched metric value is correct, not just that the key exists.
This will help catch bugs like the incorrect handling of histogram metrics.
d6bb205 to
4ffbfd6
Compare
| for metric_name in prometheus_metrics: | ||
| if metric_name in metric_samples_by_name: | ||
| # Get the latest sample for this metric | ||
| samples = metric_samples_by_name[metric_name] |
There was a problem hiding this comment.
how do we handle counters, gauges, and histogram metrics?
There was a problem hiding this comment.
Should we let the autoscaling policy handle the raw Prometheus metrics? Or you mean we need to deserialize them back into each class found in metrics.py (Counter, Gauge, Histogram)?
Otherwise, the only processing I do in _fetch_prometheus_metrics is filter metric Samples with the matching replica_id.
7362ce8 to
00239d4
Compare
| @@ -0,0 +1,266 @@ | |||
| """Utilities for fetching and parsing Prometheus metrics. | |||
There was a problem hiding this comment.
Assuming this is used by libraries? If so lets move it to _common folder.
There was a problem hiding this comment.
There's a problem with importing aiohttp outside ray serve, it appears to be blacklisted in the installation script in /ray/ci/env/check_minimal_install.py
|
|
||
| # Prometheus metrics which will be collected at each replica, which will be available in the custom AutoscalingPolicy function | ||
| # List of metric_names | ||
| prometheus_metrics: Optional[List[str]] = None |
There was a problem hiding this comment.
i believe it would be better if we can make it a field and provide description.
There was a problem hiding this comment.
also, should it be prometheus_custom_metrics as per the [doc] ?(https://docs.google.com/document/d/1KtMUDz1O3koihG6eh-QcUqudZjNAX3NsqqOMYh3BoWA/edit?tab=t.0#heading=h.l0i10kwcu7kc)
| if self._autoscaling_config and self.should_collect_ongoing_requests(): | ||
| self.start_metrics_pusher() | ||
| if self._autoscaling_config: | ||
|
|
| if self._autoscaling_config.prometheus_metrics: | ||
| self._prometheus_metrics_enabled = True | ||
| self._prometheus_queries = autoscaling_config.prometheus_metrics | ||
| self.start_metrics_pusher() | ||
| return | ||
|
|
||
| elif self.should_collect_ongoing_requests(): | ||
| self.start_metrics_pusher() | ||
| return |
There was a problem hiding this comment.
function is anyway ending here, we can just put one if condition for the
if self._autoscaling_config.prometheus_metrics:
self._prometheus_metrics_enabled = True
self._prometheus_queries = autoscaling_config.prometheus_metrics
and then we should start the metrics pusher and return
| if self._autoscaling_config.prometheus_metrics: | ||
| self._prometheus_metrics_enabled = True | ||
| self._prometheus_queries = autoscaling_config.prometheus_metrics | ||
| self.start_metrics_pusher() | ||
| return | ||
|
|
||
| elif self.should_collect_ongoing_requests(): | ||
| self.start_metrics_pusher() | ||
| return |
There was a problem hiding this comment.
| if self._autoscaling_config.prometheus_metrics: | |
| self._prometheus_metrics_enabled = True | |
| self._prometheus_queries = autoscaling_config.prometheus_metrics | |
| self.start_metrics_pusher() | |
| return | |
| elif self.should_collect_ongoing_requests(): | |
| self.start_metrics_pusher() | |
| return | |
| if self._autoscaling_config.prometheus_metrics: | |
| self._prometheus_metrics_enabled = True | |
| self._prometheus_queries = autoscaling_config.prometheus_metrics | |
| self.start_metrics_pusher() | |
| return |
There was a problem hiding this comment.
The pusher should only be started only if there's either prometheus_metrics or should_collect_ongoing_requests, otherwise each replica just pushes empty metrics and wastes compute. See #56005 (comment)
| prom_addr = RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOST | ||
| logger.debug(f"Fetching metrics from prometheus exporter at {prom_addr}") | ||
|
|
||
| metrics_text = await fetch_prometheus_metrics_async( |
There was a problem hiding this comment.
is there any prometheus API which can return us the exact metrics we are looking for? IIUC, this will fetch all prom metrics in our memory, and then we will find the metrics which are helpful to us.
There was a problem hiding this comment.
In my first implementation it will query the Prometheus Server which supported PromQL filtering. However as you say this current implementation will get everything from Prometheus Exporter. As Abrar suggested I will switch back to the first original implementation.
7dc7e58 to
efa5df7
Compare
| "RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE": "0", | ||
| "RAY_SERVE_REPLICA_AUTOSCALING_METRIC_RECORD_INTERVAL_S": "0.5", | ||
| "RAY_SERVE_RECORD_AUTOSCALING_STATS_TIMEOUT_S": "3", | ||
| "RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOST": "http://localhost:9090", |
There was a problem hiding this comment.
Bug: Double HTTP prefix in Prometheus URL construction
The environment variable RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOST is set to "http://localhost:9090" in the test configuration, but the fetch_from_prom_server function in prometheus_utils.py already prepends "http://" to the address parameter when constructing the URL. This results in a malformed URL like "http://http://localhost:9090/api/v1/query" with a double HTTP prefix, which will cause Prometheus queries to fail. The environment variable should be set to just "localhost:9090" without the protocol prefix.
708e4a2 to
2510071
Compare
Update (agent pass)Pushed tip
Note on full rebase onto latest master: a clean replay onto current Cursor/Gemini comment themes addressed on tip are documented in the agent review notes (DI handler, double URL prefix, hardcoded host, value extraction, early-return metrics, etc.). |
b28a362 to
1c4e48e
Compare
d7c2dc5 to
eff744f
Compare
eff744f to
a01e551
Compare
a01e551 to
dbe2074
Compare
dbe2074 to
1a24c41
Compare
3367542 to
09270c7
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
Reviewed by Cursor Bugbot for commit 09270c7. Configure here.
09270c7 to
2f3889c
Compare
Add AutoscalingConfig.prometheus_metrics and replica-side PromQL collection with a node-local TTL cache so co-located replicas sharing host/query do not N× hit Prometheus. Configured expressions are queried as-is. Prometheus JSON status=error raises instead of being treated as empty samples. Signed-off-by: Arthur Leung <[email protected]>
Core unit coverage: value extraction, co-located cache dedup, Prom error status handling, zero-TTL, and replica fetch path with co-located ids. Signed-off-by: Arthur Leung <[email protected]>
Review disposition (rebased tip)Human review threads (abrarsheikh / jjyao / harshit) are addressed on the current tip or declined with rationale:
Also on tip: raise on Prometheus JSON Rebased onto latest |
2f3889c to
193d82a
Compare

Implementation of AutoscalingConfig prometheus_custom_metrics:

Why are these changes needed?
Support collection of Prometheus exporter metrics at each replica, and report them to the controller, if the serve config AutoscalingConfig specifies.
Related issue number
Checks
git commit -s) in this PR.scripts/format.shto lint the changes in this PR.method in Tune, I've added it in
doc/source/tune/api/under thecorresponding
.rstfile.Note
Adds optional per-replica Prometheus metric collection for autoscaling, refactors Prometheus helpers into a shared module, and updates proto/config/constants/replica logic and tests.
AutoscalingConfig.prometheus_metricsis set; fetched atRAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOSTand merged into autoscaling reports.replicalabel and include alongside ongoing-requests/custom metrics.prometheus_metricstoAutoscalingConfig(Python) and new proto messagesPrometheusCustomMetrics/PrometheusMetric; map list ↔ proto on (de)serialization.RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PROMETHEUS_HOSTenv var for exporter host.python/ray/_private/prometheus_utils.pywith fetch/parse/filter helpers and async fetch; remove duplicated logic fromtest_utilsand update imports across tests/benchmarks.test_prometheus_autoscaling_metrics.py; adjust existing tests and BUILD to include env and new imports; minor test stability tweaks.Written by Cursor Bugbot for commit 02a540c. This will update automatically on new commits. Configure here.