# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Fail-closed helpers for the PLE single-slot transport.""" import functools import os import time import traceback from collections.abc import Callable from typing import Any, NoReturn, TypeVar _F = TypeVar("_F", bound=Callable[..., Any]) _TRUSTED_ERROR_LABELS = ( (RuntimeError, "RuntimeError"), (TimeoutError, "TimeoutError"), (ValueError, "ValueError"), (OSError, "OSError"), (EOFError, "EOFError"), (BrokenPipeError, "BrokenPipeError"), (AssertionError, "AssertionError"), (KeyError, "KeyError"), (IndexError, "IndexError"), (TypeError, "TypeError"), (MemoryError, "MemoryError"), (KeyboardInterrupt, "KeyboardInterrupt"), ) def ple_fail_closed( *, where: str, rank: int, layer: str, sequence: int, error: BaseException, ) -> NoReturn: """Emit one best-effort nonblocking diagnostic and terminate immediately.""" try: os.set_blocking(2, False) error_type = type(error) error_name = "Exception" trusted_error = False for trusted_type, trusted_name in _TRUSTED_ERROR_LABELS: if error_type is trusted_type: error_name = trusted_name trusted_error = True break safe_where = where[:128] if type(where) is str else "unknown" safe_layer = layer[:256] if type(layer) is str else "unknown" safe_rank = rank if type(rank) is int else -1 safe_sequence = sequence if type(sequence) is int else -1 detail_suffix = "" if trusted_error: args = BaseException.args.__get__(error, error_type) if ( type(args) is tuple and len(args) == 1 and type(args[0]) is str ): detail = args[0][:512].replace("\n", "\\n") detail_suffix = f":{detail}" message = ( f"PLE fatal: where={safe_where} rank={safe_rank} layer={safe_layer} " f"sequence={safe_sequence} error={error_name}{detail_suffix} " f"pid={os.getpid()} " f"monotonic={time.monotonic():.9f} wall={time.time():.9f}\n" ) os.write(2, message.encode("utf-8", "backslashreplace")[:2048]) except BaseException: pass # THE TRACEBACK, unconditionally, in its own try so it cannot cost us the # line above. # # This path os._exit(1)s, which runs no handlers and flushes nothing, so # whatever is not written here is gone. The line above names the TYPE only # when the type is one of _TRUSTED_ERROR_LABELS and flattens everything # else to the literal string "Exception" -- and the flattened set includes # the two that matter most here: torch.AcceleratorError (a RuntimeError # SUBCLASS, so the `is` comparison misses it) and Triton CompilationError. # An earlier boot died exactly that way: both PP0 ranks # reported "error=Exception" and there was no traceback anywhere in the # log, in any rank, so the cause could not be named at all and the next # step was a re-run rather than a fix. # # A fail-closed path is where evidence matters most, not least: it fires # once, it kills the process, and it is the only witness. Printing the type # of a wrapped exception without the frames that raised it is not a # diagnostic. try: # Three-arg form: it does not depend on being inside an active except # block, and this function is called from one frame further out than # the raise. tb = "".join( traceback.format_exception(type(error), error, error.__traceback__) ) raw = tb.encode("utf-8", "backslashreplace") # Truncate from the END, not the start. format_exception puts the # frames first and the exception TYPE AND MESSAGE last, so a head-side # cut throws away the one line that names what went wrong and keeps the # import-time frames nobody needs. A long chained traceback is exactly # the case where that matters. clipped = len(raw) > 8192 raw = raw[-8192:] os.write( 2, b"PLE fatal traceback (tail) follows:\n" if clipped else b"PLE fatal traceback follows:\n", ) os.write(2, raw) if not raw.endswith(b"\n"): os.write(2, b"\n") except BaseException: # Never silent HERE of all places: without this the reader cannot tell # "the wrapper predates the traceback fix" from "the traceback itself # could not be produced", and those call for different next steps. # Still guarded, because os._exit below must run whatever happens: an # escape from this handler would leave the worker alive in the state # the fail-closed path exists to end. try: os.write(2, b"PLE fatal: traceback unavailable\n") except BaseException: pass os._exit(1) def fail_ple_execute_model(func: _F) -> _F: """Fail a non-shutdown worker-step escape only on PLE-owning ranks. This includes ``sample_tokens``, the second half of the split execute-model step. A rank without a PLE connector rethrows the original exception. """ @functools.wraps(func) def wrapped(self: Any, *args: Any, **kwargs: Any) -> Any: try: return func(self, *args, **kwargs) except SystemExit: # WorkerProc's signal handler uses SystemExit for clean shutdown. raise except BaseException as error: connector = getattr(self, "_ple_offload_connector", None) if connector is None: model_runner = getattr(self, "model_runner", None) connector = getattr( model_runner, "_ple_offload_connector", None ) if connector is None: raise connector._fail_closed(func.__name__, error) return wrapped # type: ignore[return-value]