-
Notifications
You must be signed in to change notification settings - Fork 33
feat: add vllm sidecar heartbeat and load metrics reporting. #71
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| # Copyright 2026 The xLLM Authors. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # https://github.com/jd-opensource/xllm-service/blob/main/LICENSE | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ============================================================================== | ||
| """Scrape vLLM's Prometheus `/metrics` into the xllm-service heartbeat schema. | ||
|
|
||
| Maps vLLM gauges/histograms onto proto HeartbeatRequest fields (see | ||
| proto/xllm_rpc_service.proto LoadMetrics / LatencyMetrics): | ||
|
|
||
| vllm:num_requests_waiting -> load_metrics.waiting_requests_num | ||
| vllm:gpu_cache_usage_perc -> load_metrics.gpu_cache_usage_perc | ||
| vllm:time_to_first_token_seconds -> latency_metrics.recent_max_ttft (ms) | ||
| vllm:time_per_output_token_seconds -> latency_metrics.recent_max_tbt (ms) | ||
|
|
||
| Latency histograms only expose _sum/_count, so we report the per-interval | ||
| average (delta_sum/delta_count, in ms) as a pragmatic proxy for the proto's | ||
| "recent max" -- good enough for load-aware routing; a true max would need | ||
| bucket analysis. Metric names are pinned to vLLM 0.21. | ||
| """ | ||
|
|
||
| import logging | ||
| import math | ||
| import re | ||
|
|
||
| import requests | ||
|
|
||
| logger = logging.getLogger("vllm_sidecar.metrics") | ||
|
|
||
| # `name{labels} value [timestamp]` -> (base_name, value) | ||
| _SAMPLE_RE = re.compile( | ||
| r"^(?P<name>[a-zA-Z_:][\w:]*)(?:\{[^}]*\})?\s+" | ||
| r"(?P<value>[-+]?[0-9.eE+-]+|NaN|[-+]?Inf)\s*" | ||
| ) | ||
|
|
||
| _WAITING = "vllm:num_requests_waiting" | ||
| _GPU_CACHE = ("vllm:gpu_cache_usage_perc", "vllm:kv_cache_usage_perc") | ||
| _TTFT = "vllm:time_to_first_token_seconds" | ||
| _TBT = "vllm:time_per_output_token_seconds" | ||
|
|
||
|
|
||
| def _parse_samples(text: str) -> dict[str, float]: | ||
| """Sum sample values by base metric name (ignoring labels / HELP lines).""" | ||
| totals = {} | ||
| for line in text.splitlines(): | ||
| if not line or line[0] == "#": | ||
| continue | ||
| m = _SAMPLE_RE.match(line) | ||
| if not m: | ||
| continue | ||
| try: | ||
| val = float(m.group("value")) | ||
| except ValueError: | ||
| continue | ||
|
fdvty marked this conversation as resolved.
|
||
| # Drop NaN/Inf so downstream int()/JSON on these samples can't crash. | ||
| if not math.isfinite(val): | ||
| continue | ||
| totals[m.group("name")] = totals.get(m.group("name"), 0.0) + val | ||
| return totals | ||
|
|
||
|
|
||
| class VllmMetricsScraper: | ||
| def __init__(self, metrics_url: str, timeout: float = 3.0) -> None: | ||
| self._url = metrics_url | ||
| self._timeout = timeout | ||
| self._prev = {} # histogram base -> (sum, count) from the last scrape | ||
| # Reuse one connection across periodic scrapes (HTTP keep-alive). | ||
| self._session = requests.Session() | ||
|
|
||
| def _interval_avg_ms(self, samples: dict[str, float], base: str) -> int: | ||
| """Average over the interval since the last scrape, in ms (0 if none).""" | ||
| cur = (samples.get(base + "_sum", 0.0), samples.get(base + "_count", 0.0)) | ||
| prev = self._prev.get(base) | ||
| self._prev[base] = cur | ||
| if prev is None: | ||
| return 0 # first observation: establish baseline, no interval yet | ||
| d_count = cur[1] - prev[1] | ||
| if d_count <= 0: | ||
| return 0 | ||
| d_sum = cur[0] - prev[0] | ||
| return max(0, int((d_sum / d_count) * 1000.0)) | ||
|
|
||
| def scrape(self) -> dict | None: | ||
| """Return the heartbeat metrics dict, or None if /metrics unreachable.""" | ||
| try: | ||
| r = self._session.get(self._url, timeout=self._timeout) | ||
| r.raise_for_status() | ||
| except requests.RequestException as e: | ||
| logger.debug("metrics scrape failed: %s", e) | ||
| return None | ||
|
|
||
| s = _parse_samples(r.text) | ||
| gpu_cache = next((s[n] for n in _GPU_CACHE if n in s), 0.0) | ||
| return { | ||
| "load_metrics": { | ||
| "waiting_requests_num": int(s.get(_WAITING, 0.0)), | ||
| "gpu_cache_usage_perc": float(gpu_cache), | ||
| }, | ||
| "latency_metrics": { | ||
| "recent_max_ttft": self._interval_avg_ms(s, _TTFT), | ||
| "recent_max_tbt": self._interval_avg_ms(s, _TBT), | ||
| }, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| # Copyright 2026 The xLLM Authors. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # https://github.com/jd-opensource/xllm-service/blob/main/LICENSE | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ============================================================================== | ||
| """Unit tests for vLLM /metrics parsing (no HTTP needed).""" | ||
|
|
||
| from vllm_sidecar.metrics import VllmMetricsScraper, _parse_samples | ||
|
|
||
| SAMPLE = """\ | ||
| # HELP vllm:num_requests_waiting Number of requests waiting. | ||
| # TYPE vllm:num_requests_waiting gauge | ||
| vllm:num_requests_waiting{model_name="qwen2.5-7b"} 4.0 | ||
| # TYPE vllm:gpu_cache_usage_perc gauge | ||
| vllm:gpu_cache_usage_perc{model_name="qwen2.5-7b"} 0.37 | ||
| # TYPE vllm:time_to_first_token_seconds histogram | ||
| vllm:time_to_first_token_seconds_sum{model_name="qwen2.5-7b"} 2.0 | ||
| vllm:time_to_first_token_seconds_count{model_name="qwen2.5-7b"} 10.0 | ||
| vllm:time_per_output_token_seconds_sum{model_name="qwen2.5-7b"} 1.0 | ||
| vllm:time_per_output_token_seconds_count{model_name="qwen2.5-7b"} 100.0 | ||
| """ | ||
|
|
||
|
|
||
| def test_parse_samples_strips_labels_and_comments() -> None: | ||
| s = _parse_samples(SAMPLE) | ||
| assert s["vllm:num_requests_waiting"] == 4.0 | ||
| assert s["vllm:gpu_cache_usage_perc"] == 0.37 | ||
| assert "vllm:num_requests_waiting" in s | ||
| # HELP/TYPE comment lines must not appear | ||
| assert all(not k.startswith("#") for k in s) | ||
|
|
||
|
|
||
| def test_parse_samples_sums_duplicate_label_sets() -> None: | ||
| text = ( | ||
| 'vllm:num_requests_waiting{m="a"} 2.0\nvllm:num_requests_waiting{m="b"} 3.0\n' | ||
| ) | ||
| assert _parse_samples(text)["vllm:num_requests_waiting"] == 5.0 | ||
|
|
||
|
|
||
| def test_parse_samples_handles_scientific_notation() -> None: | ||
| # Small latency values are emitted in scientific notation with a negative | ||
| # exponent; the value must parse fully, not be truncated at "1.23e" -> 0. | ||
| text = 'vllm:time_to_first_token_seconds_sum{m="a"} 1.23e-04\n' | ||
| assert _parse_samples(text)["vllm:time_to_first_token_seconds_sum"] == 1.23e-04 | ||
|
|
||
|
|
||
| def test_parse_samples_drops_nan_and_inf() -> None: | ||
| # vLLM may emit NaN/Inf; these must be dropped so downstream int()/JSON | ||
| # cannot crash the scrape loop. | ||
| text = ( | ||
| "vllm:num_requests_waiting NaN\n" | ||
| "vllm:gpu_cache_usage_perc +Inf\n" | ||
| "vllm:other 2.0\n" | ||
| ) | ||
| s = _parse_samples(text) | ||
| assert "vllm:num_requests_waiting" not in s | ||
| assert "vllm:gpu_cache_usage_perc" not in s | ||
| assert s["vllm:other"] == 2.0 | ||
|
|
||
|
|
||
| def test_interval_avg_ms_uses_delta() -> None: | ||
| sc = VllmMetricsScraper("http://unused") | ||
| # first call establishes the baseline -> 0 | ||
| assert sc._interval_avg_ms({"h_sum": 2.0, "h_count": 10.0}, "h") == 0 | ||
| # next: delta_sum=3.0 over delta_count=5 -> 0.6s avg -> 600 ms | ||
| assert sc._interval_avg_ms({"h_sum": 5.0, "h_count": 15.0}, "h") == 600 | ||
|
|
||
|
|
||
| def test_interval_avg_ms_zero_when_no_new_samples() -> None: | ||
| sc = VllmMetricsScraper("http://unused") | ||
| sc._interval_avg_ms({"h_sum": 2.0, "h_count": 10.0}, "h") | ||
| assert sc._interval_avg_ms({"h_sum": 2.0, "h_count": 10.0}, "h") == 0 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.