Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Fix undefined behavior in kernel shutdown (#256)

Akshay Agrawal73eca2f34619
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 6e017c626a..66dba8f91c 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -1023,6 +1023,8 @@ def launch_kernel(
# install the formatter import hooks
register_formatters()
+ SHUTTING_DOWN = False
+
def interrupt_handler(signum: int, frame: Any) -> None:
"""Tries to interrupt the kernel."""
del signum
@@ -1041,8 +1043,31 @@ def launch_kernel(
del signum
del frame
+ nonlocal SHUTTING_DOWN
+ if SHUTTING_DOWN:
+ # give previous SIGTERM a chance to quit ... makes
+ # sure this method is reentrant
+ return
+ SHUTTING_DOWN = True
+
get_context().virtual_file_registry.shutdown()
- sys.exit(0)
+ # Force this process to exit.
+ #
+ # We use os._exit() instead of sys.exit() because we don't want the
+ # child process to also run atexit handlers, which may result in
+ # undefined behavior. Using sys.exit() on Linux sometimes causes
+ # the parent process to hang on shutdown, leading to orphaned
+ # processes and port.
+ #
+ # TODO(akshayka): The Python docs say this method is appropriate
+ # for processes created with fork(), but they don't say anything
+ # about processes made with spawn. macOS and Windows default to
+ # spawn. If we have further issues with clean exits, we might
+ # investigate here.
+ #
+ # https://docs.python.org/3/library/os.html#os._exit
+ # https://www.unixguide.net/unix/programming/1.1.3.shtml
+ os._exit(0)
signal.signal(signal.SIGINT, interrupt_handler)
diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.py
index 7c11d74d46..e1df1973fd 100644
--- a/marimo/_runtime/virtual_file.py
+++ b/marimo/_runtime/virtual_file.py
@@ -98,6 +98,7 @@ class VirtualFileRegistry:
registry: dict[str, shared_memory.SharedMemory] = dataclasses.field(
default_factory=dict
)
+ shutting_down = False
def __del__(self) -> None:
self.shutdown()
@@ -145,9 +146,19 @@ class VirtualFileRegistry:
del self.registry[key]
def shutdown(self) -> None:
- for _, shm in self.registry.items():
- shm.unlink()
- self.registry.clear()
+ # Try to make this method re-entrant since it's called in the
+ # sigterm handler
+ #
+ # https://www.gnu.org/software/libc/manual/html_node/Nonreentrancy.html
+ if self.shutting_down:
+ return
+ try:
+ self.shutting_down = True
+ for _, shm in self.registry.items():
+ shm.unlink()
+ self.registry.clear()
+ finally:
+ self.shutting_down = False
def _without_leading_dot(ext: str) -> str:
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 75e05d41af..4dfa505710 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -332,8 +332,13 @@ class Session:
if self.kernel_heartbeat.is_running():
self.kernel_heartbeat.stop()
if isinstance(self.kernel_task, mp.Process):
+ # type ignores:
# guaranteed to be a multiprocessing Queue; annoying to assert
# this, because mp.Queue appears to be a function
+ #
+ # don't care if queue still has things in it; don't make the
+ # child process wait for it to empty.
+ self.queue.cancel_join_thread() # type: ignore
self.queue.close() # type: ignore
if self.kernel_task.is_alive():
if (
@@ -343,6 +348,12 @@ class Session:
# since SIGTERM isn't handled on windows
os.kill(self.kernel_task.pid, signal.CTRL_BREAK_EVENT)
else:
+ # TODO(akshayka): Might be able to remove this
+ # and just rely on the fact that the kernel is a daemon
+ # process (so will terminate after this process terminates)
+ #
+ # Explicitly terminate the process, in case something
+ # prevents the server process from terminating ...
self.kernel_task.terminate()
tornado.ioloop.IOLoop.current().remove_handler(
self.read_conn.fileno()