-
Notifications
You must be signed in to change notification settings - Fork 123
feat: SLS-497 Add explicit prestart hooks to the runpod-python SDK #570
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
jasonwang-runpod
wants to merge
6
commits into
main
Choose a base branch
from
jasonwang/sls-497-explicit-prestart-hooks
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
6 commits
Select commit
Hold shift + click to select a range
f325710
feat: add prestart hook registry and failure log capture
jasonwang-runpod a48439c
feat: run prestart hooks in queue, local, and API modes
jasonwang-runpod 709f34e
docs: document prestart hooks and log capture
jasonwang-runpod 21a4221
refactor: let callers decide whether capture is enabled
jasonwang-runpod 87ad47a
test: remove scheduling sensitivity from the prestart timeout test
jasonwang-runpod be3b312
fix: address prestart review findings
jasonwang-runpod 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,149 @@ | ||
| """ | ||
| runpod | serverless | rp_capture.py | ||
|
|
||
| Captures stdout/stderr to report upon handler or prestart failure. | ||
| Swaps `sys.stdout`/`sys.stderr` for a tee proxy that writes to both the | ||
| real stream and a buffer in a contextvar. | ||
|
|
||
| Captured output is attached to failure payloads, which are returned to whoever | ||
| called the request, so capture is not on by default. `RUNPOD_LOG_CAPTURE` | ||
| selects when it runs: | ||
|
|
||
| auto (default) capture prestart failures when hooks are registered | ||
| all capture prestart and handler failures | ||
| off never capture | ||
| """ | ||
|
|
||
| import contextlib | ||
| import contextvars | ||
| import io | ||
| import os | ||
| import sys | ||
| from collections.abc import Generator | ||
|
|
||
| MAX_CAPTURED_CHARS = 16 * 1024 | ||
|
|
||
| CAPTURE_AUTO = "auto" | ||
| CAPTURE_ALL = "all" | ||
| CAPTURE_OFF = "off" | ||
| _CAPTURE_MODES = (CAPTURE_AUTO, CAPTURE_ALL, CAPTURE_OFF) | ||
|
|
||
| # 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 writelines(self, lines) -> None: | ||
| # Not covered by write(); callers that use it would otherwise bypass capture. | ||
| for line in lines: | ||
| self.write(line) | ||
|
|
||
| def flush(self) -> None: | ||
| self._real.flush() | ||
|
|
||
| def __getattr__(self, name): | ||
| # Delegate everything else to the real stream | ||
| return getattr(self._real, name) | ||
|
|
||
|
|
||
| io.TextIOBase.register(_TeeProxy) | ||
|
|
||
|
|
||
| def capture_mode() -> str: | ||
| """Resolve `RUNPOD_LOG_CAPTURE`, falling back to `auto` on anything unknown.""" | ||
| mode = os.environ.get("RUNPOD_LOG_CAPTURE", CAPTURE_AUTO).strip().lower() | ||
| return mode if mode in _CAPTURE_MODES else CAPTURE_AUTO | ||
|
|
||
|
|
||
| def handler_capture_enabled() -> bool: | ||
| """Return whether handler failure logs were explicitly enabled.""" | ||
| return capture_mode() == CAPTURE_ALL | ||
|
|
||
|
|
||
| def install(*, hooks_registered: bool = False) -> None: | ||
| """Install the tee proxy on stdout/stderr, if this worker wants capture. | ||
|
|
||
| Idempotent. `hooks_registered` is what `auto` mode keys off, and the caller | ||
| passes it in so this module stays independent of the prestart registry. | ||
| """ | ||
| mode = capture_mode() | ||
| if mode == CAPTURE_OFF: | ||
| return | ||
|
|
||
| if mode == CAPTURE_AUTO and not hooks_registered: | ||
| return | ||
|
|
||
| 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(*, enabled: bool = True) -> 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.""" | ||
| buffer = _RingBuffer() | ||
| if not enabled: | ||
| yield buffer | ||
| return | ||
|
|
||
| token = _current.set(buffer) | ||
| try: | ||
| yield buffer | ||
| finally: | ||
| # Suppress an abandoned async generator to avoid polluting stderr | ||
| with contextlib.suppress(ValueError): | ||
| _current.reset(token) | ||
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def paused() -> Generator[None]: | ||
| """Temporarily stop mirroring logs into the buffer. Currently only used to | ||
| omit diagnostic logs.""" | ||
| token = _current.set(None) | ||
| try: | ||
| yield | ||
| finally: | ||
| 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:]}" | ||
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.
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.
Registering any prestart hook flips
hooks_registered=True, which in the defaultautomode enables the stdout/stderr tee for the whole worker. Sincerun_jobalready wraps every handler incapture(), a handler that prints sensitive data and then raises will have those lines captured intoerror_info['logs']and returned to the caller in the job result.Concretely: a worker adopts an unrelated prestart hook -> capture turns on -> a handler does
print(f"HF_TOKEN={token}")then raises -> the token lands in the error payload polled by the client.The coupling (prestart-hook presence silently enables handler-failure log capture) is non-obvious and has data-exfiltration impact. Suggest decoupling: gate handler-failure capture on an explicit opt-in rather than on hook registration, or redact/scrub captured logs before embedding them in the returned error.