Skip to content

crash_guard

Keeps the terminal usable when Reloaded dies without a chance to clean up after itself, e.g. a crash in native code, and saves where a crash happened.

The terminal UI switches the terminal to its own screen, turns mouse reporting on, and reads keys raw. A process that is killed outright, or that exits from inside native code (a library that gives up with a plain exit), never switches any of that back. Nothing inside the dead process can fix that, and nothing outside it can do it quickly enough: a shell started from a script sees the script exit normally, so it keeps the terminal as it finds it, raw, and starts its line editor there. The line editor takes a terminal with echo off to mean that echo is wanted off, so it shows nothing that is typed, and it keeps that state for every later prompt. A helper process woken the instant Reloaded died still lost that race to the shell.

So the command runs Reloaded as a child process and waits for it. The parent is part of the job the shell is waiting for, so it can put the terminal right before the shell gets it back. The child tells the parent, through a pipe, when the terminal UI session starts and when it has finished cleaning up, which is how the parent knows whether the terminal needs putting right.

It also turns on Python's fault handler, so a crash writes the Python stack of every thread to a file, which is what is needed to find out where it happened.

RESET_TERMINAL module-attribute

Python
RESET_TERMINAL = "\x1b[?1049l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1005l\x1b[?1006l\x1b[?1015l\x1b[?1004l\x1b[?2004l\x1b[?2026l\x1b[<9u\x1b[?1l\x1b>\x1b[?7h\x1b[?25h\x1b[0m"

What to send a terminal to undo everything the terminal UI turns on.

SUPERVISED module-attribute

Python
SUPERVISED = 'MOJO_RELOADED_SUPERVISED'

Set in the environment of the process that does the work, so it does not supervise itself.

PROGRESS_FD module-attribute

Python
PROGRESS_FD = 'MOJO_RELOADED_PROGRESS_FD'

Set in the environment of the process that does the work, to the number of the pipe it reports its progress through.

CrashGuard dataclass

Python
CrashGuard(crash_path: Path)

Around the terminal UI: saves the stack of every thread to crash_path if the process crashes. Leaves no file behind after a normal exit.

crash_path instance-attribute

Python
crash_path: Path

Where the stacks of a crash are written.

current_tty

Python
current_tty() -> str | None

The path of the terminal Reloaded is running in, or None when there is no terminal to look after (output is piped, or this is not a Unix system).

Source code in src/mujoco_mojo/utils/layers/crash_guard.py
Python
def current_tty() -> str | None:
    """The path of the terminal Reloaded is running in, or `None` when there is no terminal to look after (output is piped, or this is not a Unix system)."""
    if os.name != "posix":
        return None
    try:
        return os.ttyname(sys.stdin.fileno())
    except (OSError, ValueError):
        return None

restore_terminal

Python
restore_terminal(
    tty_path: str, saved: Any, message: str = ""
) -> None

Puts the terminal at tty_path back the way it was: its input settings as saved (from termios.tcgetattr), and its screen modes reset. Prints message afterwards, if there is one.

Source code in src/mujoco_mojo/utils/layers/crash_guard.py
Python
def restore_terminal(tty_path: str, saved: Any, message: str = "") -> None:
    """Puts the terminal at `tty_path` back the way it was: its input settings as `saved` (from `termios.tcgetattr`), and its screen modes reset. Prints `message` afterwards, if there is one."""
    import termios

    fd = os.open(tty_path, os.O_RDWR | os.O_NOCTTY)
    try:
        termios.tcsetattr(fd, termios.TCSANOW, saved)
        os.write(fd, (RESET_TERMINAL + message).encode())
    finally:
        os.close(fd)

crash_message

Python
crash_message(crash_path: Path, status: int) -> str

What to tell the user after Reloaded stopped without cleaning up, including where the stacks went if a crash left any. status is the child's, negative for a signal.

Source code in src/mujoco_mojo/utils/layers/crash_guard.py
Python
def crash_message(crash_path: Path, status: int) -> str:
    """What to tell the user after Reloaded stopped without cleaning up, including where the stacks went if a crash left any. `status` is the child's, negative for a signal."""
    if status < 0:
        try:
            how = f"killed by {signal.Signals(-status).name}"
        except ValueError:
            how = f"killed by signal {-status}"
    else:
        how = f"exit status {status}"
    message = f"\r\nReloaded stopped without cleaning up after itself ({how}), so the terminal was reset.\r\n"
    try:
        if crash_path.stat().st_size > 0:
            message += f"Python's stack for every thread was saved to {crash_path}\r\n"
    except OSError:
        pass
    return message

run_supervised

Python
run_supervised(crash_path: Path) -> int | None

Runs the command that is running now again, as a child process, waits for it, and gives the status to exit with. If the child was killed, or stopped in the middle of the terminal UI session without finishing it, the terminal is put right first.

Gives None when that is not wanted, which means the caller should just carry on and do the work: this already is the child, or there is no terminal to look after.

Source code in src/mujoco_mojo/utils/layers/crash_guard.py
Python
def run_supervised(crash_path: Path) -> int | None:
    """
    Runs the command that is running now again, as a child process, waits for it, and gives the status to exit with. If the child was killed, or stopped in the middle of the terminal UI session without finishing it, the terminal is put right first.

    Gives `None` when that is not wanted, which means the caller should just carry on and do the work: this already is the child, or there is no terminal to look after.
    """
    if os.environ.get(SUPERVISED):
        _adopt_progress_pipe()
        return None
    tty_path = current_tty()
    if tty_path is None:
        return None
    import termios

    try:
        fd = os.open(tty_path, os.O_RDWR | os.O_NOCTTY)
        saved = termios.tcgetattr(fd)
        os.close(fd)
    except (OSError, termios.error):
        return None

    progress_in, progress_out = os.pipe()
    try:
        # the very command line, so the child is exactly what would have run
        child = subprocess.Popen(
            sys.orig_argv,
            env={**os.environ, SUPERVISED: "1", PROGRESS_FD: str(progress_out)},
            pass_fds=(progress_out,),
        )
    except BaseException:
        os.close(progress_in)
        raise
    finally:
        os.close(progress_out)
    # a Ctrl+C reaches both, and what it means is for the child to decide. set after the child starts,
    # because an ignored signal stays ignored in a process that is started from this one
    previous = {signal.SIGINT: signal.signal(signal.SIGINT, signal.SIG_IGN)}
    for forwarded in (signal.SIGTERM, signal.SIGHUP):
        previous[forwarded] = signal.signal(
            forwarded, lambda number, frame: child.send_signal(number)
        )
    try:
        status = child.wait()
        progress = _read_progress(progress_in)
    finally:
        os.close(progress_in)
        for number, handler in previous.items():
            signal.signal(number, handler)

    unfinished = STARTED in progress and FINISHED not in progress
    if status < 0 or unfinished:
        try:
            restore_terminal(tty_path, saved, crash_message(crash_path, status))
        except OSError:
            # the terminal itself is gone, e.g. the window was closed, and there is nothing left to restore
            pass
    return 128 - status if status < 0 else status