-
Notifications
You must be signed in to change notification settings - Fork 3.2k
feat(telemetry): MVP support for opt-in telemetry of runner crashes #2126
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
AndreiCravtov
wants to merge
20
commits into
main
Choose a base branch
from
andrei/telem
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
Show all changes
20 commits
Select commit
Hold shift + click to select a range
a972339
runner-unique paths
AndreiCravtov b67e989
telemetry skeleton
AndreiCravtov f387f54
supervisor wiring
AndreiCravtov 354aa1b
no more todo
AndreiCravtov 536f69b
clone
AndreiCravtov 6969c21
wired up telemetry
AndreiCravtov a806371
plumbing
AndreiCravtov 73dfde5
send runner log
AndreiCravtov ec25092
end-to-end runs
AndreiCravtov 56c2536
skip zero
AndreiCravtov 97b6953
test
AndreiCravtov 2e4b13c
undo
AndreiCravtov e629007
test
AndreiCravtov 50d02f3
fee
AndreiCravtov 0df3df6
undo logging
AndreiCravtov 5810819
Merge branch 'main' into andrei/telem
AndreiCravtov d8b752b
push changes
AndreiCravtov 490cf32
fix env flag
AndreiCravtov fe2f6c9
Merge branch 'main' into andrei/telem
AndreiCravtov a295eb8
fixes
AndreiCravtov 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
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,176 @@ | ||
| import contextlib | ||
| import hashlib | ||
| from dataclasses import dataclass, field | ||
| from pathlib import Path | ||
| from typing import Self | ||
| from urllib.parse import urlparse | ||
|
|
||
| import httpx | ||
| from anyio import BrokenResourceError, ClosedResourceError, WouldBlock, to_thread | ||
| from loguru import logger | ||
|
|
||
| from exo.shared.constants import EXO_TELEMETRY_API_URL | ||
| from exo.utils.channels import Receiver, Sender, channel | ||
| from exo.utils.pydantic_ext import FrozenModel, TaggedModel | ||
| from exo.utils.task_group import TaskGroup | ||
|
|
||
| CHANNEL_BOUND_SIZE = 64 | ||
| TELEMETRY_HTTP_TIMEOUT_SECONDS = 10.0 | ||
|
|
||
|
|
||
| class BaseTelemetrySubmission(TaggedModel): | ||
| pass | ||
|
|
||
|
|
||
| class TestSubmission(BaseTelemetrySubmission): | ||
| pass | ||
|
|
||
|
|
||
| class RunnerStderrSubmission(BaseTelemetrySubmission): | ||
| path: Path | ||
|
|
||
|
|
||
| TelemetrySubmission = TestSubmission | RunnerStderrSubmission | ||
|
|
||
|
|
||
| class TelemetryPresignResponse(FrozenModel): | ||
| key: str | ||
| upload_url: str | ||
| expires_in: int | ||
| max_size: int | ||
|
|
||
|
|
||
| @dataclass(eq=False) | ||
| class TelemetrySink: | ||
| """ | ||
| A non-blocking non-throwing bounded wrapper around sender/receiver channels | ||
| to ensure telemetry never blocks or has adverse side-effects, since telemetry | ||
| is an optional diagnostic feature and hence should never break the main app. | ||
| """ | ||
|
|
||
| _send: Sender[TelemetrySubmission] | ||
|
|
||
| @classmethod | ||
| def pair(cls) -> tuple[Self, Receiver[TelemetrySubmission]]: | ||
| send, recv = channel[TelemetrySubmission](CHANNEL_BOUND_SIZE) | ||
| return cls(_send=send), recv | ||
|
|
||
| def submit(self, submission: TelemetrySubmission): | ||
| try: | ||
| self._send.send_nowait(submission) | ||
| except WouldBlock: | ||
| logger.debug("Telemetry submission would block. why so many submissions??") | ||
| except (BrokenResourceError, ClosedResourceError): | ||
| logger.debug("Telemetry submission receivers are broken or closed. why??") | ||
|
|
||
| def clone(self) -> "TelemetrySink": | ||
| return TelemetrySink(_send=self._send.clone()) | ||
|
|
||
| def close(self): | ||
| with contextlib.suppress(BrokenResourceError, ClosedResourceError): | ||
| self._send.close() | ||
|
|
||
|
|
||
| @dataclass(eq=False) | ||
| class TelemetryService: | ||
| telemetry_disabled: bool | ||
| api_url: str | ||
| _send: Sender[TelemetrySubmission] | ||
| _recv: Receiver[TelemetrySubmission] | ||
| _http_transport: httpx.AsyncBaseTransport | None | ||
| _tg: TaskGroup = field(default_factory=TaskGroup, init=False) | ||
|
|
||
| @classmethod | ||
| def create( | ||
| cls, | ||
| telemetry_disabled: bool, | ||
| api_url: str = EXO_TELEMETRY_API_URL, | ||
| http_transport: httpx.AsyncBaseTransport | None = None, | ||
| ) -> Self: | ||
| api_url = urlparse(api_url).geturl().rstrip("/") | ||
|
|
||
| send, recv = channel[TelemetrySubmission](CHANNEL_BOUND_SIZE) | ||
|
|
||
| return cls( | ||
| telemetry_disabled=telemetry_disabled, | ||
| api_url=api_url, | ||
| _send=send, | ||
| _recv=recv, | ||
| _http_transport=http_transport, | ||
| ) | ||
|
|
||
| @classmethod | ||
| def dummy(cls) -> Self: | ||
| return cls.create(True) | ||
|
|
||
| async def run(self): | ||
| try: | ||
| async with self._tg as tg: | ||
| tg.start_soon(self._process) | ||
| finally: | ||
| self._send.close() | ||
| self._recv.close() | ||
|
|
||
| async def _process(self): | ||
| with self._recv as submissions: | ||
| async for submission in submissions: | ||
| if not self.telemetry_disabled: | ||
| try: | ||
| await self._process_submission(submission) | ||
| except Exception as e: | ||
| logger.opt(exception=e).warning( | ||
| "Exception when processing telemetry submission" | ||
| ) | ||
|
|
||
| async def _process_submission(self, submission: TelemetrySubmission): | ||
| match submission: | ||
| case TestSubmission(): | ||
| pass | ||
| case RunnerStderrSubmission(path=path): | ||
| await self._submit_runner_stderr(path) | ||
|
|
||
| async def _submit_runner_stderr(self, path: Path): | ||
| data = await to_thread.run_sync(path.read_bytes) | ||
| if not data: | ||
| logger.debug(f"Skipping empty runner stderr telemetry file: {path}") | ||
| return | ||
|
|
||
| sha256 = hashlib.sha256(data).hexdigest() | ||
|
|
||
| async with httpx.AsyncClient( | ||
| timeout=TELEMETRY_HTTP_TIMEOUT_SECONDS, | ||
| transport=self._http_transport, | ||
| ) as client: | ||
| presign_response = await client.post( | ||
| f"{self.api_url}/telemetry/runner-log/presign", | ||
| json={ | ||
| "sha256": sha256, | ||
| "size": len(data), | ||
| }, | ||
| ) | ||
| presign_response.raise_for_status() | ||
| presign = TelemetryPresignResponse.model_validate_json( | ||
| presign_response.text, | ||
| ) | ||
|
|
||
| upload_response = await client.put( | ||
| presign.upload_url, | ||
| content=data, | ||
| ) | ||
| upload_response.raise_for_status() | ||
|
|
||
| def sink(self) -> TelemetrySink: | ||
| sink, recv = TelemetrySink.pair() | ||
| if self._tg.is_running(): | ||
| self._tg.start_soon(self._ingest, recv) | ||
| else: | ||
| self._tg.queue(self._ingest, recv) | ||
| return sink | ||
|
|
||
| async def _ingest(self, recv: Receiver[TelemetrySubmission]): | ||
| try: | ||
| with recv as submissions: | ||
| async for submission in submissions: | ||
| await self._send.send(submission) | ||
| except ClosedResourceError: | ||
| 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import hashlib | ||
| import json | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
|
|
||
| import httpx | ||
| import pytest | ||
|
|
||
| from exo.shared.telemetry import RunnerStderrSubmission, TelemetryService | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class RecordedRequest: | ||
| method: str | ||
| url: str | ||
| content: bytes | ||
|
|
||
|
|
||
| def _queue_submission( | ||
| service: TelemetryService, | ||
| submission: RunnerStderrSubmission, | ||
| ) -> None: | ||
| service._send.send_nowait(submission) # pyright: ignore[reportPrivateUsage] | ||
| service._send.close() # pyright: ignore[reportPrivateUsage] | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| async def test_runner_stderr_upload_hashes_and_uploads_file_bytes(tmp_path: Path): | ||
| log_bytes = b"runner stderr\nsecond line\n" | ||
| log_path = tmp_path / "runner.stderr.log" | ||
| log_path.write_bytes(log_bytes) | ||
| requests: list[RecordedRequest] = [] | ||
|
|
||
| async def handler(request: httpx.Request) -> httpx.Response: | ||
| requests.append( | ||
| RecordedRequest( | ||
| method=request.method, | ||
| url=str(request.url), | ||
| content=await request.aread(), | ||
| ) | ||
| ) | ||
| if request.method == "POST": | ||
| return httpx.Response( | ||
| 200, | ||
| json={ | ||
| "key": "runner_log/test.stderr.log", | ||
| "uploadUrl": "https://uploads.example/runner.stderr.log", | ||
| "expiresIn": 300, | ||
| "maxSize": 52428800, | ||
| }, | ||
| ) | ||
| if request.method == "PUT": | ||
| return httpx.Response(200) | ||
| return httpx.Response(404) | ||
|
|
||
| service = TelemetryService.create( | ||
| telemetry_disabled=False, | ||
| api_url="https://telemetry.example/", | ||
| http_transport=httpx.MockTransport(handler), | ||
| ) | ||
|
|
||
| await service._process_submission( # pyright: ignore[reportPrivateUsage] | ||
| RunnerStderrSubmission(path=log_path) | ||
| ) | ||
|
|
||
| assert [r.method for r in requests] == ["POST", "PUT"] | ||
| assert requests[0].url == "https://telemetry.example/telemetry/runner-log/presign" | ||
| assert json.loads(requests[0].content) == { | ||
| "sha256": hashlib.sha256(log_bytes).hexdigest(), | ||
| "size": len(log_bytes), | ||
| } | ||
| assert requests[1].url == "https://uploads.example/runner.stderr.log" | ||
| assert requests[1].content == log_bytes | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| async def test_runner_stderr_upload_failure_is_swallowed(tmp_path: Path): | ||
| log_path = tmp_path / "runner.stderr.log" | ||
| log_path.write_text("runner stderr\n") | ||
| requests: list[httpx.Request] = [] | ||
|
|
||
| async def handler(request: httpx.Request) -> httpx.Response: | ||
| requests.append(request) | ||
| return httpx.Response(500) | ||
|
|
||
| service = TelemetryService.create( | ||
| telemetry_disabled=False, | ||
| api_url="https://telemetry.example", | ||
| http_transport=httpx.MockTransport(handler), | ||
| ) | ||
| _queue_submission(service, RunnerStderrSubmission(path=log_path)) | ||
|
|
||
| await service._process() # pyright: ignore[reportPrivateUsage] | ||
|
|
||
| assert len(requests) == 1 |
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.