-
Notifications
You must be signed in to change notification settings - Fork 550
feat(serve): expose env server / worker stats on /metrics Prometheus endpoint #1415
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
Open
mvanhorn
wants to merge
1
commit into
PrimeIntellect-ai:main
Choose a base branch
from
mvanhorn:fix/1188-prometheus-metrics-env-server
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import asyncio | ||
| import http.client | ||
|
|
||
| import pytest | ||
|
|
||
| from verifiers.serve.server.env_router import EnvRouterStats | ||
| from verifiers.serve.server.env_worker import EnvWorkerStats | ||
| from verifiers.serve.server.metrics import MetricsServer, render_prometheus_text | ||
|
|
||
|
|
||
| def test_render_prometheus_text_smoke(): | ||
| stats = EnvRouterStats( | ||
| workers={ | ||
| 0: EnvWorkerStats(worker_id=0, timestamp=0.0, active_tasks=3), | ||
| 1: EnvWorkerStats(worker_id=1, timestamp=0.0, active_tasks=5), | ||
| } | ||
| ) | ||
|
|
||
| body = render_prometheus_text(stats, env_id="math-python", version="0.1.15") | ||
|
|
||
| assert "verifiers_env_active_tasks 8" in body | ||
| assert "verifiers_env_workers_total 2" in body | ||
| assert 'verifiers_env_worker_active_tasks{worker_id="0"} 3' in body | ||
| assert 'verifiers_env_worker_active_tasks{worker_id="1"} 5' in body | ||
| assert 'verifiers_env_server_info{env_id="math-python",version="0.1.15"} 1' in body | ||
| assert 'verifiers_env_loop_lag_seconds{worker_id="0",quantile="p95"} 0.0' in body | ||
| assert body.endswith("\n") | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_metrics_server_serves_metrics(unused_tcp_port): | ||
| class StubRouter: | ||
| stats = EnvRouterStats( | ||
| workers={0: EnvWorkerStats(worker_id=0, timestamp=0.0, active_tasks=2)} | ||
| ) | ||
|
|
||
| server = MetricsServer( | ||
| StubRouter(), env_id="test", version="dev", port=unused_tcp_port | ||
| ) | ||
| await server.start() | ||
| try: | ||
|
|
||
| def fetch(): | ||
| conn = http.client.HTTPConnection("127.0.0.1", unused_tcp_port, timeout=2) | ||
| conn.request("GET", "/metrics") | ||
| response = conn.getresponse() | ||
| return response.status, response.read().decode() | ||
|
|
||
| status, body = await asyncio.get_running_loop().run_in_executor(None, fetch) | ||
|
|
||
| assert status == 200 | ||
| assert "verifiers_env_active_tasks 2" in body | ||
| assert "verifiers_env_workers_total 1" in body | ||
| finally: | ||
| await server.close() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_metrics_server_404_on_other_path(unused_tcp_port): | ||
| class StubRouter: | ||
| stats = EnvRouterStats(workers={}) | ||
|
|
||
| server = MetricsServer(StubRouter(), env_id="t", version="x", port=unused_tcp_port) | ||
| await server.start() | ||
| try: | ||
|
|
||
| def fetch(): | ||
| conn = http.client.HTTPConnection("127.0.0.1", unused_tcp_port, timeout=2) | ||
| conn.request("GET", "/") | ||
| return conn.getresponse().status | ||
|
|
||
| status = await asyncio.get_running_loop().run_in_executor(None, fetch) | ||
|
|
||
| assert status == 404 | ||
| finally: | ||
| await server.close() |
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
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
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,135 @@ | ||
| """Prometheus text-format metrics for env server stats.""" | ||
|
|
||
| import asyncio | ||
| import logging | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| if TYPE_CHECKING: | ||
| from verifiers.serve.server.env_router import EnvRouter, EnvRouterStats | ||
|
|
||
| from verifiers.utils.async_utils import EventLoopLagStats | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _escape_label_value(value: str) -> str: | ||
| return value.replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"') | ||
|
|
||
|
|
||
| def _lag_quantiles(lag: EventLoopLagStats) -> dict[str, float]: | ||
| return { | ||
| "p50": lag.median, | ||
| "p95": lag.p95, | ||
| "p99": lag.p99, | ||
| } | ||
|
|
||
|
|
||
| def render_prometheus_text( | ||
| router_stats: "EnvRouterStats", *, env_id: str, version: str | ||
| ) -> str: | ||
| """Render an EnvRouterStats snapshot as Prometheus text exposition format.""" | ||
| escaped_env_id = _escape_label_value(env_id) | ||
| escaped_version = _escape_label_value(version) | ||
| lines: list[str] = [ | ||
| "# HELP verifiers_env_server_info Env server build and identity labels.", | ||
| "# TYPE verifiers_env_server_info gauge", | ||
| ( | ||
| "verifiers_env_server_info" | ||
| f'{{env_id="{escaped_env_id}",version="{escaped_version}"}} 1' | ||
| ), | ||
| "# HELP verifiers_env_active_tasks Total active rollouts across workers.", | ||
| "# TYPE verifiers_env_active_tasks gauge", | ||
| f"verifiers_env_active_tasks {router_stats.active_tasks}", | ||
| "# HELP verifiers_env_workers_total Configured worker count.", | ||
| "# TYPE verifiers_env_workers_total gauge", | ||
| f"verifiers_env_workers_total {router_stats.num_workers}", | ||
| "# HELP verifiers_env_worker_active_tasks Active rollouts per worker.", | ||
| "# TYPE verifiers_env_worker_active_tasks gauge", | ||
| ] | ||
|
|
||
| for worker_id, worker_stats in sorted(router_stats.workers.items()): | ||
| active_tasks = worker_stats.active_tasks if worker_stats is not None else 0 | ||
| lines.append( | ||
| f'verifiers_env_worker_active_tasks{{worker_id="{worker_id}"}} {active_tasks}' | ||
| ) | ||
|
|
||
| lines.extend( | ||
| [ | ||
| "# HELP verifiers_env_loop_lag_seconds Asyncio event loop lag in seconds.", | ||
| "# TYPE verifiers_env_loop_lag_seconds gauge", | ||
| ] | ||
| ) | ||
| for quantile, value in _lag_quantiles(router_stats.lag).items(): | ||
| lines.append( | ||
| "verifiers_env_loop_lag_seconds" | ||
| f'{{worker_id="router",quantile="{quantile}"}} {value}' | ||
| ) | ||
| for worker_id, worker_stats in sorted(router_stats.workers.items()): | ||
| if worker_stats is None: | ||
| continue | ||
| for quantile, value in _lag_quantiles(worker_stats.lag).items(): | ||
| lines.append( | ||
| "verifiers_env_loop_lag_seconds" | ||
| f'{{worker_id="{worker_id}",quantile="{quantile}"}} {value}' | ||
| ) | ||
|
|
||
| return "\n".join(lines) + "\n" | ||
|
|
||
|
|
||
| class MetricsServer: | ||
| """Asyncio HTTP server serving /metrics in Prometheus text format.""" | ||
|
|
||
| def __init__( | ||
| self, router: "EnvRouter", *, env_id: str, version: str, port: int | ||
| ) -> None: | ||
| self.router = router | ||
| self.env_id = env_id | ||
| self.version = version | ||
| self.port = port | ||
| self.server: asyncio.AbstractServer | None = None | ||
|
|
||
| async def start(self) -> None: | ||
| self.server = await asyncio.start_server(self.handle, "0.0.0.0", self.port) | ||
| logger.info(f"Metrics server listening on http://0.0.0.0:{self.port}/metrics") | ||
|
|
||
| async def close(self) -> None: | ||
| if self.server is None: | ||
| return | ||
| self.server.close() | ||
| await self.server.wait_closed() | ||
| self.server = None | ||
|
|
||
| async def handle( | ||
| self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter | ||
| ) -> None: | ||
| try: | ||
| request_line = await reader.readline() | ||
| while True: | ||
| line = await reader.readline() | ||
| if line in (b"\r\n", b"\n", b""): | ||
| break | ||
|
|
||
| parts = request_line.split() | ||
| if len(parts) < 2 or parts[0] != b"GET" or parts[1] != b"/metrics": | ||
| writer.write(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n") | ||
| else: | ||
| body = render_prometheus_text( | ||
| self.router.stats, | ||
| env_id=self.env_id, | ||
| version=self.version, | ||
| ).encode("utf-8") | ||
| headers = ( | ||
| b"HTTP/1.1 200 OK\r\n" | ||
| b"Content-Type: text/plain; version=0.0.4; charset=utf-8\r\n" | ||
| + f"Content-Length: {len(body)}\r\n\r\n".encode() | ||
| ) | ||
| writer.write(headers + body) | ||
| await writer.drain() | ||
| except Exception: | ||
| logger.exception("Metrics server request handling failed") | ||
| finally: | ||
| writer.close() | ||
| try: | ||
| await writer.wait_closed() | ||
| except Exception: | ||
| pass |
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
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OpenEnv start_server rejects metrics_port
High Severity
run_evaluationalways passesmetrics_portintostart_server, butOpenEnvEnv.start_serverdoes not declare that keyword and does not forward it toEnvironment.start_server. Evaluations that useOpenEnvEnvwith the env server enabled raiseTypeErroron startup, even when metrics are disabled.Reviewed by Cursor Bugbot for commit df7e644. Configure here.