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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: pyodide interrupts (#921)
Akshay Agrawalbc4f1cc074a2
diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.tsindex 2c2b390aa8..3b7b78fb50 100644--- a/frontend/src/core/pyodide/bridge.ts+++ b/frontend/src/core/pyodide/bridge.ts@@ -51,6 +51,7 @@ export class PyodideBridge implements RunRequests, EditRequests {static INSTANCE = new PyodideBridge();private worker!: Worker;+ private interruptBuffer?: Uint8Array;private messageConsumer: ((message: string) => void) | undefined;private fetcher = new DeferredRequestRegistry<BridgeFunctionAndPayload,@@ -70,6 +71,19 @@ export class PyodideBridge implements RunRequests, EditRequests {if (isPyodide()) {this.worker = new InlineWorker();this.worker.onmessage = this.handleWorkerMessage;+ if (crossOriginIsolated) {+ // Pyodide handles interrupts through SharedArrayBuffers, which+ // only work in secure (crossOriginIsolated) contexts+ this.interruptBuffer = new Uint8Array(new SharedArrayBuffer(1));+ this.fetcher.request({+ functionName: "set_interrupt_buffer",+ payload: this.interruptBuffer,+ });+ } else {+ console.warn(+ "Not running in a secure context; interrupts are not available.",+ );+ }}}private setCode = async () => {@@ -167,10 +181,10 @@ export class PyodideBridge implements RunRequests, EditRequests {return null;};sendInterrupt = async (): Promise<null> => {- await this.fetcher.request({- functionName: "interrupt",- payload: undefined,- });+ if (this.interruptBuffer !== undefined) {+ // 2 sends a SIGINT+ this.interruptBuffer[0] = 2;+ }return null;};sendShutdown = async (): Promise<null> => {diff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.tsindex 1d0f7782ef..674fb30ce7 100644--- a/frontend/src/core/pyodide/worker/types.ts+++ b/frontend/src/core/pyodide/worker/types.ts@@ -18,7 +18,7 @@ import type {export interface RawBridge {put_control_request(operation: object): Promise<string>;put_input(input: string): Promise<string>;- interrupt(): Promise<string>;+ interrupt(buffer: Uint8Array): Promise<string>;code_complete(request: CodeCompletionRequest): Promise<string>;read_code(): Promise<{ contents: string }>;format(request: FormatRequest): Promise<FormatResponse>;@@ -38,6 +38,7 @@ export interface RawBridge {): Promise<FileOperationResponse>;load_packages(request: string): Promise<string>;read_file(request: string): Promise<string>;+ set_interrupt_buffer(request: Uint8Array): Promise<string>;}export type SerializedBridge = {diff --git a/frontend/src/core/pyodide/worker/worker.ts b/frontend/src/core/pyodide/worker/worker.tsindex 5de5efcb8a..5594a7370c 100644--- a/frontend/src/core/pyodide/worker/worker.ts+++ b/frontend/src/core/pyodide/worker/worker.ts@@ -93,6 +93,17 @@ self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {postMessage({ type: "response", response: file, id });return;}++ // Special case for installing the interrupt buffer+ if (functionName == "set_interrupt_buffer") {+ invariant(+ payload instanceof Uint8Array,+ "Expected a Uint8Array payload for interrupt",+ );+ self.pyodide.setInterruptBuffer(payload);+ postMessage({ type: "response", response: null, id });+ return;+ }// Special case to lazily install black on format// Don't return early; still need to ask the pyodide kernel to run// the formatterdiff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 945c1cb0ad..f06645cca5 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -100,6 +100,10 @@ export default defineConfig({},},},+ headers: {+ "Cross-Origin-Opener-Policy": "same-origin",+ "Cross-Origin-Embedder-Policy": "require-corp",+ },},resolve: {dedupe: ["react", "react-dom", "@emotion/react", "@emotion/cache"],diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 048a4dd656..a5f0ecc03f 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport dataclassesimport json+import signalfrom typing import Any, Callable, Optionalfrom marimo import _loggers@@ -16,7 +17,7 @@ from marimo._pyodide.streams import (PyodideStdout,PyodideStream,)-from marimo._runtime import requests+from marimo._runtime import handlers, requestsfrom marimo._runtime.context import initialize_contextfrom marimo._runtime.input_override import input_overridefrom marimo._runtime.requests import (@@ -175,10 +176,6 @@ class PyodideSession:) -> None:self._queue_manager.completion_queue.put_nowait(request)- def interrupt(self) -> None:- assert self.kernel_task is not None- self.kernel_task.restart()-def put_input(self, text: str) -> None:self._queue_manager.input_queue.put_nowait(text)@@ -202,9 +199,6 @@ class PyodideBridge:def put_input(self, text: str) -> None:self.session.put_input(text)- def interrupt(self) -> None:- self.session.interrupt()-def code_complete(self, request: str) -> None:parsed = parse_raw(json.loads(request), requests.CompletionRequest)self.session.put_completion_request(parsed)@@ -321,9 +315,9 @@ def launch_pyodide_kernel()if is_edit_mode:- from marimo._output.formatters.formatters import register_formatters-- register_formatters()+ signal.signal(+ signal.SIGINT, handlers.construct_interrupt_handler(kernel)+ )async def listen_messages() -> None:while True:diff --git a/marimo/_runtime/handlers.py b/marimo/_runtime/handlers.pynew file mode 100644index 0000000000..a0be8d9a90--- /dev/null+++ b/marimo/_runtime/handlers.py@@ -0,0 +1,75 @@+# Copyright 2024 Marimo. All rights reserved.+import os+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Callable++from marimo import _loggers+from marimo._messaging.ops import Interrupted+from marimo._runtime.context import get_context+from marimo._runtime.control_flow import MarimoInterrupt++LOGGER = _loggers.marimo_logger()++if TYPE_CHECKING:+ from marimo._runtime.runtime import Kernel+++def construct_interrupt_handler(+ kernel: "Kernel",+) -> Callable[[int, Any], None]:+ def interrupt_handler(signum: int, frame: Any) -> None:+ """Tries to interrupt the kernel."""+ del signum+ del frame++ LOGGER.debug("Interrupt request received")+ # TODO(akshayka): if kernel is in `run` but not executing,+ # it won't be interrupted, which isn't right ... but the+ # probability of that happening is low.+ if kernel.execution_context is not None:+ Interrupted().broadcast()+ raise MarimoInterrupt++ return interrupt_handler+++def construct_sigterm_handler(kernel: "Kernel") -> Callable[[int, Any], None]:+ del kernel++ @dataclass+ class Bit:+ value: bool = False++ shutting_down = Bit()++ def sigterm_handler(signum: int, frame: Any) -> None:+ """Cleans up the kernel ands exit."""+ del signum+ del frame++ if shutting_down.value:+ # give previous SIGTERM a chance to quit ... makes+ # sure this method is reentrant+ return+ shutting_down.value = True++ get_context().virtual_file_registry.shutdown()+ # 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)++ return sigterm_handlerdiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex e352f4b2f7..ecb380ad04 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -35,7 +35,6 @@ from marimo._messaging.ops import (CompletedRun,FunctionCallResult,HumanReadableStatus,- Interrupted,RemoveUIElements,VariableDeclaration,Variables,@@ -60,7 +59,13 @@ from marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import MarimoConvertValueException-from marimo._runtime import cell_runner, dataflow, marimo_pdb, patches+from marimo._runtime import (+ cell_runner,+ dataflow,+ handlers,+ marimo_pdb,+ patches,+)from marimo._runtime.complete import complete, completion_workerfrom marimo._runtime.context import (ContextNotInitializedError,@@ -1207,59 +1212,19 @@ def launch_kernel(# install the formatter import hooksregister_formatters()- SHUTTING_DOWN = False-- def interrupt_handler(signum: int, frame: Any) -> None:- """Tries to interrupt the kernel."""- del signum- del frame-- LOGGER.debug("interrupt request received")- # TODO(akshayka): if kernel is in `run` but not executing,- # it won't be interrupted, which isn't right ... but the- # probability of that happening is low.- if kernel.execution_context is not None:- Interrupted().broadcast()- raise MarimoInterrupt-- def sigterm_handler(signum: int, frame: Any) -> None:- """Cleans up the kernel ands exit."""- 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()- # 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)+ signal.signal(+ signal.SIGINT, handlers.construct_interrupt_handler(kernel)+ )if sys.platform == "win32" or sys.platform == "cygwin":# windows doesn't handle SIGTERM- signal.signal(signal.SIGBREAK, sigterm_handler)+ signal.signal(+ signal.SIGBREAK, handlers.construct_sigterm_handler(kernel)+ )else:- signal.signal(signal.SIGTERM, sigterm_handler)+ signal.signal(+ signal.SIGTERM, handlers.construct_sigterm_handler(kernel)+ )async def control_loop() -> None:while True: