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
improvement: flush sync in wasm instead of async (#868)
Myles Scolnick83820e83d91e
diff --git a/frontend/src/core/pyodide/worker/bootstrap.ts b/frontend/src/core/pyodide/worker/bootstrap.tsindex b8a76aa130..ace832ceda 100644--- a/frontend/src/core/pyodide/worker/bootstrap.ts+++ b/frontend/src/core/pyodide/worker/bootstrap.ts@@ -31,7 +31,7 @@ export async function bootstrap() {const marimoWheel =process.env.NODE_ENV === "production"? "marimo >= 0.2.5"- : "http://localhost:8000/dist/marimo-0.2.9-py3-none-any.whl";+ : "http://localhost:8000/dist/marimo-0.2.10-py3-none-any.whl";await pyodide.runPythonAsync(`import micropip@@ -56,10 +56,19 @@ export async function startSession(fallbackCode: string;filename: string | null;},+ messageCallback: (data: string) => void,): Promise<SerializedBridge> {// Set up the filesystemconst { filename, content } = await mountFilesystem({ pyodide, ...opts });+ // We pass down a messenger object to the code+ // This is used to have synchronous communication between the JS and Python code+ // Previously, we used a queue, but this would not properly flush the queue+ // during processing of a cell's code.+ //+ // This adds a messenger object to the global scope (import js; js.messenger.callback)+ self.messenger = { callback: messageCallback };+// Load packages from the codeawait pyodide.loadPackagesFromImports(content, {messageCallback: Logger.log,@@ -70,14 +79,19 @@ export async function startSession(`print("[py] Starting marimo...")import asyncio+ import jsfrom marimo._pyodide.pyodide_session import create_session, instantiate- session, bridge = create_session(filename="${filename}")+ assert js.messenger, "messenger is not defined"++ session, bridge = create_session(filename="${filename}", message_callback=js.messenger.callback)instantiate(session)asyncio.create_task(session.start())bridge`,);+ self.bridge = bridge;+return bridge;}diff --git a/frontend/src/core/pyodide/worker/message-buffer.ts b/frontend/src/core/pyodide/worker/message-buffer.tsnew file mode 100644index 0000000000..5d18fd5484--- /dev/null+++ b/frontend/src/core/pyodide/worker/message-buffer.ts@@ -0,0 +1,32 @@+/* Copyright 2024 Marimo. All rights reserved. */++/**+ * A buffer for messages that are received before the worker is ready to process them.+ * Once the worker is ready, the buffer is flushed.+ */+export class MessageBuffer<T> {+ private buffer: T[];+ private started = false;++ constructor(private onMessage: (data: T) => void) {+ this.buffer = [];+ }++ push = (data: T) => {+ if (this.started) {+ this.onMessage(data);+ } else {+ this.buffer.push(data);+ }+ };++ /**+ * Start processing messages+ */+ start = () => {+ this.started = true;+ // Flush the buffer+ this.buffer.forEach((data) => this.onMessage(data));+ this.buffer = [];+ };+}diff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.tsindex 80a75f791f..1d0f7782ef 100644--- a/frontend/src/core/pyodide/worker/types.ts+++ b/frontend/src/core/pyodide/worker/types.ts@@ -38,7 +38,6 @@ export interface RawBridge {): Promise<FileOperationResponse>;load_packages(request: string): Promise<string>;read_file(request: string): Promise<string>;- [Symbol.asyncIterator](): AsyncIterator<string>;}export type SerializedBridge = {diff --git a/frontend/src/core/pyodide/worker/worker.ts b/frontend/src/core/pyodide/worker/worker.tsindex 45a914adb4..5f04d757d4 100644--- a/frontend/src/core/pyodide/worker/worker.ts+++ b/frontend/src/core/pyodide/worker/worker.ts@@ -11,6 +11,7 @@ import {import { invariant } from "../../../utils/invariant";import { Deferred } from "../../../utils/Deferred";import { syncFileSystem } from "./fs";+import { MessageBuffer } from "./message-buffer";declare const self: Window & {pyodide: PyodideInterface;@@ -23,6 +24,9 @@ async function loadPyodideAndPackages() {self.pyodide = await bootstrap();}const pyodideReadyPromise = loadPyodideAndPackages();+const messageBuffer = new MessageBuffer((m: string) =>+ postMessage({ type: "message", message: m }),+);// Initialize the sessionconst bridgeReady = new Deferred<SerializedBridge>();@@ -36,11 +40,12 @@ function startSessionWithCode(opts: {return;}started = true;- startSession(self.pyodide, opts).then((bridge) => {+ startSession(self.pyodide, opts, messageBuffer.push).then((bridge) => {bridgeReady.resolve(bridge);postMessage({ type: "initialized" });});}+async function getBridge() {return bridgeReady.promise;}@@ -55,16 +60,9 @@ self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {return;}- // Run forever, waiting for messages from the Python bridgeif (event.data.type === "start-messages") {- const done = false;-- while (!done) {- const bridge = await getBridge();- for await (const message of bridge) {- postMessage({ type: "message", message });- }- }+ // Flush the message buffer+ messageBuffer.start();return;}diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex d9cdb9e6b5..c6906cf61c 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -227,7 +227,11 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):vega_spec["autosize"] = "fit-x"# Selection for binned charts is not yet implemented- if _has_binning(vega_spec):+ has_chart_selection = chart_selection is not False+ has_legend_selection = legend_selection is not False+ if _has_binning(vega_spec) and (+ has_chart_selection or has_legend_selection+ ):sys.stderr.write("Binning + selection is not yet supported in ""marimo.ui.chart.\n"diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 9d261cf5a1..048a4dd656 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -73,18 +73,14 @@ def instantiate(session: PyodideSession) -> None:def create_session(filename: str,+ message_callback: Callable[[str], None],) -> tuple[PyodideSession, PyodideBridge]:- queue = asyncio.Queue[dict[str, Any]]()-def write_kernel_message(op: KernelMessage) -> None:- queue.put_nowait({"op": op[0], "data": op[1]})+ message_callback(json.dumps({"op": op[0], "data": op[1]}))app_file_manager = AppFileManager(filename=filename)app = app_file_manager.app-- app_metadata = AppMetadata(- filename=filename,- )+ app_metadata = AppMetadata(filename=filename)session = PyodideSession(app_file_manager, SessionMode.EDIT, write_kernel_message, app_metadata@@ -108,7 +104,7 @@ def create_session())- bridge = PyodideBridge(queue, session)+ bridge = PyodideBridge(session)return session, bridge@@ -190,18 +186,11 @@ class PyodideSession:class PyodideBridge:def __init__(self,- queue: asyncio.Queue[dict[str, Any]],session: PyodideSession,):- self.queue = queueself.session = sessionself.file_system = OSFileSystem()- async def __aiter__(self) -> Any:- while True:- op = await self.queue.get()- yield json.dumps(op)-def put_control_request(self, request: str) -> None:@dataclasses.dataclassclass Container:diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.pyindex c7129cc8fa..4265ec356e 100644--- a/marimo/_pyodide/streams.py+++ b/marimo/_pyodide/streams.py@@ -157,7 +157,7 @@ class PyodideStdin(Stdin):CellOp(cell_id=self.stream.cell_id,console=CellOutput(- channel=CellChannel.STDERR,+ channel=CellChannel.STDIN,mimetype="text/plain",data=prompt,),