-
Notifications
You must be signed in to change notification settings - Fork 121
feat: SLS-494 sdk supervises worker initialization code #567
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
Draft
jasonwang-runpod
wants to merge
2
commits into
main
Choose a base branch
from
jasonwang/sls-494-sdk-initializer
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.
Draft
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,91 @@ | ||
| """ | ||
| runpod | serverless | rp_capture.py | ||
|
|
||
| Captures stdout/stderr, to be reported upon handler or initializer failure. | ||
| Swaps `sys.stdout`/`sys.stderr` for a tee proxy that writes to both the | ||
| real stream and a buffer in a contextvar. | ||
| """ | ||
|
|
||
| import contextlib | ||
| import contextvars | ||
| import sys | ||
| from collections.abc import Generator | ||
|
|
||
| MAX_CAPTURED_CHARS = 16 * 1024 | ||
|
|
||
| # Capture buffer for the current context | ||
| _current: "contextvars.ContextVar[_RingBuffer | None]" = contextvars.ContextVar( | ||
| "rp_stdio_capture", default=None | ||
| ) | ||
|
|
||
|
|
||
|
|
||
| class _RingBuffer: | ||
| """Keeps only the last `limit` characters since the tail is usually where the | ||
| failure reason is.""" | ||
|
|
||
| def __init__(self, limit: int = MAX_CAPTURED_CHARS): | ||
| self.limit = limit | ||
| self._buf = "" | ||
|
|
||
| def write(self, text: str) -> int: | ||
| self._buf = (self._buf + text)[-self.limit :] | ||
| return len(text) | ||
|
|
||
| def getvalue(self) -> str: | ||
| return self._buf | ||
|
|
||
|
|
||
| class _TeeProxy: | ||
| """Forwards to the real stream and mirrors into its buffer.""" | ||
|
|
||
| def __init__(self, real): | ||
| self._real = real | ||
|
|
||
| def write(self, text) -> int: | ||
| n = self._real.write(text) | ||
| buffer = _current.get() | ||
| if buffer is not None: | ||
| with contextlib.suppress(Exception): | ||
| buffer.write(text) | ||
| return n | ||
|
|
||
| def flush(self) -> None: | ||
| self._real.flush() | ||
|
|
||
| def __getattr__(self, name): | ||
| # Delegate everything else to the real stream | ||
| return getattr(self._real, name) | ||
|
|
||
|
|
||
| def install() -> None: | ||
| """Install the tee proxy on stdout/stderr. Idempotent.""" | ||
| if not isinstance(sys.stdout, _TeeProxy): | ||
| sys.stdout = _TeeProxy(sys.stdout) | ||
| if not isinstance(sys.stderr, _TeeProxy): | ||
| sys.stderr = _TeeProxy(sys.stderr) | ||
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def capture() -> Generator[_RingBuffer]: | ||
| """Capture stdout/stderr written within this context (and within threads it spawns via | ||
| `asyncio.to_thread`), while still passing everything through to the real streams. | ||
|
|
||
| Yields the buffer; call `.getvalue()` for the captured text.""" | ||
| buffer = _RingBuffer() | ||
| token = _current.set(buffer) | ||
| try: | ||
| yield buffer | ||
| finally: | ||
| # Suppress an abandoned async generator to avoid polluting stderr | ||
| with contextlib.suppress(ValueError): | ||
| _current.reset(token) | ||
|
|
||
|
|
||
| def clip(text: str, limit: int = MAX_CAPTURED_CHARS) -> str: | ||
| """Truncate an error string, keeping the head and tail (the useful parts).""" | ||
| if not text or len(text) <= limit: | ||
| return text | ||
| keep = limit // 2 | ||
| omitted = len(text) - 2 * keep | ||
| return f"{text[:keep]}\n...[{omitted} characters truncated]...\n{text[-keep:]}" |
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,133 @@ | ||
| """ | ||
| runpod | serverless | initializer | ||
|
|
||
| Runs the user's startup initialization code concurrently with the job loop. | ||
| The loop may take a request right away, but the handler is not called until the initializer | ||
| finishes. On failure or timeout, the error + stdout/stderr are attached to | ||
| the current request. | ||
|
|
||
| A sync/blocking initializer is offloaded to a worker thread so it does not starve the | ||
| loop; an async one is awaited directly. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import contextlib | ||
| import contextvars | ||
| import inspect | ||
| import threading | ||
| import traceback | ||
| from collections.abc import Callable | ||
| from typing import Any | ||
|
|
||
| from runpod.serverless.modules.rp_capture import MAX_CAPTURED_CHARS, clip | ||
| from runpod.serverless.modules.rp_logger import RunPodLogger | ||
| from runpod.serverless.modules.worker_state import WORKER_ID | ||
| from runpod.version import __version__ as runpod_version | ||
|
|
||
| log = RunPodLogger() | ||
|
|
||
| INIT_FAILED_EVENT = "init_failed" | ||
|
|
||
|
|
||
| class InitializerTimeout(Exception): | ||
| """Raised when the initializer exceeds `init_timeout`.""" | ||
|
|
||
|
|
||
| class InitializerError(Exception): | ||
| """Wraps any exception raised by the user's initializer.""" | ||
|
|
||
| def __init__(self, original: BaseException): | ||
| self.original = original | ||
| super().__init__(str(original)) | ||
|
|
||
|
|
||
| def build_init_failed_payload(exc: BaseException, logs: str = "") -> dict[str, Any]: | ||
| """Failure reason as a structured dict, using the same core fields as a handler error | ||
| (type, message, traceback). `logs` contains stdout/stderr.""" | ||
| original = getattr(exc, "original", exc) | ||
| payload = { | ||
| "event": INIT_FAILED_EVENT, | ||
| "error_type": type(original).__name__, | ||
| "error_message": clip(str(original)), | ||
| "error_traceback": clip( | ||
| "".join( | ||
| traceback.format_exception( | ||
| type(original), original, original.__traceback__ | ||
| ) | ||
| ) | ||
| ), | ||
| "worker_id": WORKER_ID, | ||
| "runpod_version": runpod_version, | ||
| } | ||
| if logs: | ||
| payload["logs"] = logs[-MAX_CAPTURED_CHARS:] | ||
| return payload | ||
|
|
||
|
|
||
| async def _run_sync_in_daemon(fn: Callable) -> Any: | ||
| """Run a blocking callable on a daemon thread instead of `asyncio.to_thread` so if stuck, | ||
| it can be abandoned and die without blocking executor shutdown or process exit.""" | ||
| loop = asyncio.get_running_loop() | ||
| done = asyncio.Event() | ||
| results: list[Any] = [] | ||
| errors: list[BaseException] = [] | ||
| ctx = contextvars.copy_context() | ||
|
|
||
| def worker(): | ||
| try: | ||
| results.append(ctx.run(fn)) | ||
| except Exception as exc: # noqa: BLE001 - transferred to the event loop below | ||
| errors.append(exc) | ||
| except ( | ||
| KeyboardInterrupt, | ||
| SystemExit, | ||
| GeneratorExit, | ||
| asyncio.CancelledError, | ||
| ) as exc: | ||
| errors.append(exc) | ||
| finally: | ||
| with contextlib.suppress(RuntimeError): | ||
| loop.call_soon_threadsafe(done.set) | ||
|
|
||
| threading.Thread(target=worker, name="rp-initializer", daemon=True).start() | ||
| await done.wait() | ||
| if errors: | ||
| raise errors[0] | ||
| return results[0] if results else None | ||
|
|
||
|
|
||
| async def _invoke_initializer(initializer: Callable) -> None: | ||
| if inspect.iscoroutinefunction(initializer) or inspect.iscoroutinefunction( | ||
| initializer.__call__ | ||
| ): | ||
| result = initializer() | ||
| else: | ||
| result = await _run_sync_in_daemon(initializer) | ||
|
|
||
| if inspect.isawaitable(result): | ||
| await result | ||
|
jasonwang-runpod marked this conversation as resolved.
|
||
|
|
||
|
|
||
| async def run_initializer_async( | ||
| initializer: Callable, timeout: int | None = None | ||
| ) -> None: | ||
| """Run the initializer to completion inside the running event loop, raising | ||
| `InitializerTimeout` on timeout or `InitializerError` for any other failure.""" | ||
| log.info("Initializer | init started") | ||
| try: | ||
| awaitable = _invoke_initializer(initializer) | ||
| if timeout is not None: | ||
| await asyncio.wait_for(awaitable, timeout=timeout) | ||
| else: | ||
| await awaitable | ||
| except asyncio.TimeoutError as exc: | ||
| raise InitializerTimeout( | ||
| f"initializer exceeded init_timeout of {timeout}s" | ||
| ) from exc | ||
| except (InitializerError, InitializerTimeout): | ||
| raise | ||
| except SystemExit as exc: | ||
| raise InitializerError(exc) from exc | ||
| except Exception as exc: | ||
| raise InitializerError(exc) from exc | ||
| log.info("Initializer | ready") | ||
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.
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.