-
Notifications
You must be signed in to change notification settings - Fork 1.5k
[OPIK-5282] [SDK] feat: capture runner job stdout/stderr and stream to backend #5976
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
petrotiurin
merged 6 commits into
main
from
petrot/OPIK-5282-fix-signal-handlers-main-thread
Mar 31, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7fd821e
[OPIK-5282] [SDK] fix: install signal handlers on main thread in acti…
petrotiurin 9bb6048
[OPIK-5282] [SDK] feat: capture runner job stdout/stderr and stream t…
petrotiurin aa68cff
fix(runner): graceful LogStreamer shutdown and closed-loop guard
petrotiurin 9918814
fix(runner): address PR review comments
petrotiurin f353a3c
Merge branch 'main' into petrot/OPIK-5282-fix-signal-handlers-main-th…
petrotiurin 63f5bb7
Merge branch 'main' into petrot/OPIK-5282-fix-signal-handlers-main-th…
petrotiurin 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,20 @@ | ||
| """Per-job context tracking using contextvars (works in both asyncio and threads).""" | ||
|
|
||
| import contextvars | ||
| from typing import Optional | ||
|
|
||
| _job_id_var: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar( | ||
| "runner_job_id", default=None | ||
| ) | ||
|
|
||
|
|
||
| def get_current_job_id() -> Optional[str]: | ||
| return _job_id_var.get() | ||
|
|
||
|
|
||
| def set_job_id(job_id: str) -> contextvars.Token: | ||
| return _job_id_var.set(job_id) | ||
|
|
||
|
|
||
| def reset_job_id(token: contextvars.Token) -> None: | ||
| _job_id_var.reset(token) |
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,120 @@ | ||
| """Captures stdout/stderr per-job and streams to the backend asynchronously.""" | ||
|
|
||
| import asyncio | ||
| import io | ||
| import logging | ||
| import sys | ||
| import typing | ||
|
|
||
| from .context import get_current_job_id | ||
| from ..rest_api.client import OpikApi | ||
| from ..rest_api.types.local_runner_log_entry import LocalRunnerLogEntry | ||
|
|
||
| LOGGER = logging.getLogger(__name__) | ||
|
|
||
| _FLUSH_INTERVAL_SECONDS = 0.5 | ||
|
|
||
|
|
||
| class _CaptureStream(io.TextIOBase): | ||
| """Intercepts writes, captures per-job log entries, forwards to the inner stream.""" | ||
|
|
||
| encoding: str = "utf-8" | ||
|
|
||
| def __init__( | ||
| self, | ||
| stream: typing.TextIO, | ||
| stream_name: str, | ||
| loop: asyncio.AbstractEventLoop, | ||
| queue: asyncio.Queue, | ||
| ) -> None: | ||
| self._stream = stream | ||
| self._stream_name = stream_name | ||
| self._loop = loop | ||
| self._queue = queue | ||
| self.encoding = getattr(stream, "encoding", "utf-8") | ||
|
|
||
| def write(self, s: str) -> int: | ||
| if s.strip(): | ||
| job_id = get_current_job_id() | ||
| if job_id is not None: | ||
| entry = LocalRunnerLogEntry(stream=self._stream_name, text=s) | ||
| try: | ||
| self._loop.call_soon_threadsafe( | ||
| self._queue.put_nowait, (job_id, entry) | ||
| ) | ||
| except RuntimeError: | ||
| pass | ||
| return self._stream.write(s) | ||
|
petrotiurin marked this conversation as resolved.
|
||
|
|
||
| def flush(self) -> None: | ||
| self._stream.flush() | ||
|
|
||
| def isatty(self) -> bool: | ||
| return self._stream.isatty() | ||
|
|
||
| def fileno(self) -> int: | ||
| return self._stream.fileno() | ||
|
|
||
|
|
||
| class LogStreamer: | ||
| def __init__(self, api: OpikApi, loop: asyncio.AbstractEventLoop) -> None: | ||
| self._api = api | ||
| self._loop = loop | ||
| self._queue: asyncio.Queue[typing.Tuple[str, LocalRunnerLogEntry]] = ( | ||
| asyncio.Queue() | ||
| ) | ||
| self._task: typing.Optional[asyncio.Task] = None | ||
|
|
||
| def install(self) -> None: | ||
| sys.stdout = _CaptureStream(sys.stdout, "stdout", self._loop, self._queue) # type: ignore[assignment] | ||
|
petrotiurin marked this conversation as resolved.
|
||
| sys.stderr = _CaptureStream(sys.stderr, "stderr", self._loop, self._queue) # type: ignore[assignment] | ||
|
|
||
| def start(self) -> None: | ||
| self._task = self._loop.create_task(self._run()) | ||
|
|
||
| async def stop(self) -> None: | ||
| if self._task is not None: | ||
| self._task.cancel() | ||
| try: | ||
| await self._task | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| async def _run(self) -> None: | ||
| pending: typing.Dict[str, typing.List[LocalRunnerLogEntry]] = {} | ||
|
|
||
| while True: | ||
| try: | ||
| job_id, entry = await asyncio.wait_for( | ||
| self._queue.get(), timeout=_FLUSH_INTERVAL_SECONDS | ||
| ) | ||
| pending.setdefault(job_id, []).append(entry) | ||
|
|
||
| if self._queue.empty(): | ||
| await self._drain_all(pending) | ||
|
petrotiurin marked this conversation as resolved.
|
||
| except asyncio.TimeoutError: | ||
| await self._drain_all(pending) | ||
| except asyncio.CancelledError: | ||
| await self._drain_all(pending) | ||
| return | ||
|
|
||
| async def _drain_all( | ||
| self, pending: typing.Dict[str, typing.List[LocalRunnerLogEntry]] | ||
| ) -> None: | ||
| for job_id in list(pending): | ||
| entries = pending.pop(job_id) | ||
| if entries: | ||
| await self._send_batch(job_id, entries) | ||
|
|
||
| async def _send_batch( | ||
| self, job_id: str, entries: typing.List[LocalRunnerLogEntry] | ||
| ) -> None: | ||
| try: | ||
| await self._loop.run_in_executor( | ||
| None, | ||
| lambda: self._api.runners.append_job_logs( | ||
| job_id=job_id, request=entries | ||
| ), | ||
| ) | ||
| except Exception: | ||
| LOGGER.debug("Failed to send logs for job %s", job_id, exc_info=True) | ||
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
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.