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
Merge SetUIElementRequests on the backend (#1374)
Akshay Agrawalf5e51df262c5
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex e81f74419a..da41f8d21a 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -41,7 +41,6 @@ import useEvent from "react-use-event-hook";import { CellEditor } from "./cell/code/cell-editor";import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";import { outputIsStale } from "@/core/cells/cell";-import { RuntimeState } from "@/core/kernel/RuntimeState";import { isOutputEmpty } from "@/core/cells/outputs";import { useHotkeysOnElement, useKeydownOnElement } from "@/hooks/useHotkey";import { useSetAtom } from "jotai";@@ -205,10 +204,8 @@ const CellComponent = (const code = prepareToRunEffects();- RuntimeState.INSTANCE.registerRunStart();await sendRun([cellId], [code]).catch((error) => {Logger.error("Error running cell", error);- RuntimeState.INSTANCE.registerRunEnd();});});diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.tsindex 4bb0dc9bbb..76cc964ae7 100644--- a/frontend/src/components/editor/cell/useRunCells.ts+++ b/frontend/src/components/editor/cell/useRunCells.ts@@ -1,5 +1,4 @@/* Copyright 2024 Marimo. All rights reserved. */-import { RuntimeState } from "@/core/kernel/RuntimeState";import { CellId } from "@/core/cells/ids";import { sendRun } from "@/core/network/requests";import { staleCellIds, useNotebook } from "@/core/cells/cells";@@ -52,10 +51,8 @@ function useRunCells() {ref.registerRun();}- RuntimeState.INSTANCE.registerRunStart();await sendRun(cellIds, codes).catch((error) => {Logger.error(error);- RuntimeState.INSTANCE.registerRunEnd();});});diff --git a/frontend/src/components/editor/package-alert.tsx b/frontend/src/components/editor/package-alert.tsxindex a66ce1e43d..dd59931543 100644--- a/frontend/src/components/editor/package-alert.tsx+++ b/frontend/src/components/editor/package-alert.tsx@@ -13,7 +13,6 @@ import { saveUserConfig } from "@/core/network/requests";import { UserConfig, UserConfigSchema } from "../../core/config/config-schema";import { NativeSelect } from "../ui/native-select";import { cn } from "@/utils/cn";-import { RuntimeState } from "@/core/kernel/RuntimeState";import { sendInstallMissingPackages } from "@/core/network/requests";import {useAlerts,@@ -246,9 +245,7 @@ async function installPackages(clearPackageAlert: () => void,) {clearPackageAlert();- RuntimeState.INSTANCE.registerRunStart();await sendInstallMissingPackages({ manager: manager }).catch((error) => {- RuntimeState.INSTANCE.registerRunEnd();Logger.error(error);});}diff --git a/frontend/src/core/functions/FunctionRegistry.ts b/frontend/src/core/functions/FunctionRegistry.tsindex 0eca3d26c9..c880366f2a 100644--- a/frontend/src/core/functions/FunctionRegistry.ts+++ b/frontend/src/core/functions/FunctionRegistry.ts@@ -1,6 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import { RuntimeState } from "@/core/kernel/RuntimeState";import { sendFunctionRequest } from "@/core/network/requests";import { FunctionCallResultMessage } from "../kernel/messages";import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";@@ -11,12 +10,10 @@ export const FUNCTIONS_REGISTRY = new DeferredRequestRegistry<FunctionCallResultMessage>("function-call-result", async (requestId, req) => {// RPC counts as a kernel invocation- RuntimeState.INSTANCE.registerRunStart();await sendFunctionRequest({functionCallId: requestId,...req,}).catch((error) => {- RuntimeState.INSTANCE.registerRunEnd();throw error;});});diff --git a/frontend/src/core/islands/components/output-wrapper.tsx b/frontend/src/core/islands/components/output-wrapper.tsxindex 72fd6d4de2..12f5f08efe 100644--- a/frontend/src/core/islands/components/output-wrapper.tsx+++ b/frontend/src/core/islands/components/output-wrapper.tsx@@ -6,7 +6,6 @@ import { NotebookState, notebookAtom } from "@/core/cells/cells";import { CellId } from "@/core/cells/ids";import { isOutputEmpty } from "@/core/cells/outputs";import { CellRuntimeState } from "@/core/cells/types";-import { RuntimeState } from "@/core/kernel/RuntimeState";import { sendRun } from "@/core/network/requests";import { useEventListener } from "@/hooks/useEventListener";import { Logger } from "@/utils/Logger";@@ -111,10 +110,8 @@ export const MarimoOutputWrapper: React.FC<Props> = ({tooltip="Re-run cell"icon={<PlayIcon className="size-3" />}action={async () => {- RuntimeState.INSTANCE.registerRunStart();await sendRun([cellId], [codeCallback()]).catch((error) => {Logger.error(error);- RuntimeState.INSTANCE.registerRunEnd();});}}/>diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.tsindex dda88f7d08..4b6bde0c7c 100644--- a/frontend/src/core/islands/main.ts+++ b/frontend/src/core/islands/main.ts@@ -17,8 +17,6 @@ import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";import {handleKernelReady,- handleCompletedRun,- handleInterrupted,handleRemoveUIElements,handleCellOperation,} from "../kernel/handlers";@@ -77,10 +75,8 @@ export async function initialize() {defineCustomElement(MarimoIslandElement.tagName, MarimoIslandElement);return;case "completed-run":- handleCompletedRun();return;case "interrupted":- handleInterrupted();return;case "remove-ui-elements":handleRemoveUIElements(msg.data);diff --git a/frontend/src/core/kernel/RuntimeState.ts b/frontend/src/core/kernel/RuntimeState.tsindex 66a1ff106b..756307dc95 100644--- a/frontend/src/core/kernel/RuntimeState.ts+++ b/frontend/src/core/kernel/RuntimeState.ts@@ -4,9 +4,9 @@ import {MarimoValueReadyEventType,} from "../dom/events";import { UI_ELEMENT_REGISTRY, UIElementRegistry } from "../dom/uiregistry";-import { isStaticNotebook } from "../static/static-state";import { RunRequests } from "../network/types";import { repl } from "@/utils/repl";+import { Logger } from "@/utils/Logger";/*** Manager to track running cells.@@ -17,23 +17,12 @@ export class RuntimeState {*/static readonly INSTANCE = new RuntimeState(UI_ELEMENT_REGISTRY);- // TODO(akshayka): move the running-count state machine to the Python kernel;- // keeping track of it in the frontend is very brittle. the kernel can simply- // choose to drop queued update requests when newer ones arrive- /**- * number of cells that are currently running, to implement debouncing- * and batching of update requests- */- private runningCount: number;/*** ObjectIds of UIElements whose values need to be updated in the kernel*/- private componentsToUpdate: Set<string>;private _sendComponentValues: RunRequests["sendComponentValues"] | undefined;constructor(private uiElementRegistry: UIElementRegistry) {- this.runningCount = 0;- this.componentsToUpdate = new Set();repl(RuntimeState.INSTANCE, "RuntimeState");}@@ -59,57 +48,22 @@ export class RuntimeState {document.removeEventListener(marimoValueReadyEvent, this.handleReadyEvent);}- registerRunStart(): void {- this.runningCount += 1;- }-- registerRunEnd(): void {- // Threshold runningCount to 0 for resiliency. Won't be needed once- // we merge UI component updates in Python- this.runningCount = Math.max(this.runningCount - 1, 0);- }-- running(): boolean {- return this.runningCount > 0 && !isStaticNotebook();- }-- flushUpdates() {- if (this.componentsToUpdate.size > 0) {- // Start a run- this.registerRunStart();-- // Store the components to update, in case the run fails to be sent- const previousComponentsToUpdate = new Set(this.componentsToUpdate);-- this.sendComponentValues(- Array.from(this.componentsToUpdate.values(), (objectId) => ({- objectId: objectId,- value: this.uiElementRegistry.lookupValue(objectId),- })).filter((update) => update.value !== undefined),- ).catch(() => {- // This happens if the run was failed to register (401, 403, network error, etc.)- // If the run fails, restore the components to update and finish the run- // A run may fail if the kernel is restarted or the notebook is closed,- // but if we don't restore registerRunEnd() will never be able to flush updates.- this.registerRunEnd();- // Merge the previous components to update with the current ones- previousComponentsToUpdate.forEach((objectId) =>- this.componentsToUpdate.add(objectId),- );- });- this.componentsToUpdate.clear();- }- }-private handleReadyEvent = (e: MarimoValueReadyEventType) => {const objectId = e.detail.objectId;if (!this.uiElementRegistry.has(objectId)) {return;}- this.componentsToUpdate.add(objectId);- if (!this.running()) {- this.flushUpdates();+ const value = this.uiElementRegistry.lookupValue(objectId);+ if (value !== undefined) {+ this.sendComponentValues([{ objectId: objectId, value: value }]).catch(+ // This happens if the run failed to register (401, 403, network+ // error, etc.) A run may fail if the kernel is restarted or the+ // notebook is closed.+ (error) => {+ Logger.warn(error);+ },+ );}};}diff --git a/frontend/src/core/kernel/__tests__/RuntimeState.test.ts b/frontend/src/core/kernel/__tests__/RuntimeState.test.tsindex de6ed6bedf..312d929a51 100644--- a/frontend/src/core/kernel/__tests__/RuntimeState.test.ts+++ b/frontend/src/core/kernel/__tests__/RuntimeState.test.ts@@ -4,12 +4,6 @@ import { UIElementRegistry } from "@/core/dom/uiregistry";import { describe, beforeEach, expect, vi, test, MockedFunction } from "vitest";import { RuntimeState } from "../RuntimeState";import { RunRequests } from "@/core/network/types";-import { UIElementId } from "@/core/cells/ids";--const elementOne = document.createElement("div");-const uiElementOneId = "uiElementOne" as UIElementId;-const elementTwo = document.createElement("div");-const uiElementTwoId = "uiElementTwo" as UIElementId;const addEventListenerSpy = vi.spyOn(document, "addEventListener");const removeEventListenerSpy = vi.spyOn(document, "removeEventListener");@@ -45,128 +39,4 @@ describe("RuntimeState", () => {expect.any(Function),);});-- test("registerRunStart should increment runningCount", () => {- runtimeState.registerRunStart();- expect(runtimeState.running()).toBe(true);- });-- test("registerRunEnd should decrement runningCount", () => {- runtimeState.registerRunStart();- runtimeState.registerRunStart();- runtimeState.registerRunEnd();- expect(runtimeState.running()).toBe(true); // still running- runtimeState.registerRunEnd();- expect(runtimeState.running()).toBe(false); // not running- });-- test("flushUpdates should not call sendComponentValues if no updates", () => {- runtimeState.flushUpdates();- expect(mockSendComponentValues).not.toHaveBeenCalled();- });-- test("flushUpdates should call sendComponentValues with updates", async () => {- runtimeState.start(mockSendComponentValues);- uiElementRegistry.registerInstance(uiElementOneId, elementOne);- expect(uiElementRegistry.entries).toHaveLength(1);- expect(mockSendComponentValues).not.toHaveBeenCalled();-- uiElementRegistry.broadcastValueUpdate(elementOne, uiElementOneId, "10");- expect(mockSendComponentValues).toHaveBeenCalledOnce();- expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`- [- {- "objectId": "uiElementOne",- "value": "10",- },- ]- `);- expect(runtimeState.running()).toBe(true);- });-- test("will only send one broadcast at a time and hold future events", () => {- runtimeState.start(mockSendComponentValues);- uiElementRegistry.registerInstance(uiElementOneId, elementOne);- uiElementRegistry.registerInstance(uiElementTwoId, elementTwo);- uiElementRegistry.broadcastValueUpdate(elementOne, uiElementOneId, "10");- // Set while running- uiElementRegistry.broadcastValueUpdate(elementTwo, uiElementTwoId, "20");- uiElementRegistry.broadcastValueUpdate(elementOne, uiElementOneId, "30");- expect(mockSendComponentValues).toHaveBeenCalledOnce();- expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`- [- {- "objectId": "uiElementOne",- "value": "10",- },- ]- `);- expect(runtimeState.running()).toBe(true);-- // End run- runtimeState.registerRunEnd();- expect(runtimeState.running()).toBe(false);-- // Start another run, this overwrites the previous value that was not sent- uiElementRegistry.broadcastValueUpdate(elementTwo, uiElementTwoId, "40");- expect(mockSendComponentValues).toHaveBeenCalledTimes(2);- // We expect 2 values to be sent, the last value of uiElementTwo and the last value of uiElementOne- // both that were set while running- expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`- [- {- "objectId": "uiElementTwo",- "value": "40",- },- {- "objectId": "uiElementOne",- "value": "30",- },- ]- `);- expect(runtimeState.running()).toBe(true);- });-- test("handle when sendComponentValues fails", async () => {- runtimeState.start(mockSendComponentValues);- uiElementRegistry.registerInstance(uiElementOneId, elementOne);- uiElementRegistry.registerInstance(uiElementTwoId, elementTwo);- expect(uiElementRegistry.entries).toHaveLength(2);- expect(mockSendComponentValues).not.toHaveBeenCalled();-- const error = new Error("Failed to send component values");- mockSendComponentValues.mockRejectedValueOnce(error);-- uiElementRegistry.broadcastValueUpdate(elementOne, uiElementOneId, "10");- // flush the event loop- await new Promise((resolve) => setTimeout(resolve, 10));- expect(mockSendComponentValues).toHaveBeenCalledOnce();- expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`- [- {- "objectId": "uiElementOne",- "value": "10",- },- ]- `);-- // It should not be running anymore- expect(runtimeState.running()).toBe(false);-- // And if we try another element, we should send both (since the previous one failed)- uiElementRegistry.broadcastValueUpdate(elementTwo, uiElementTwoId, "20");- expect(mockSendComponentValues).toHaveBeenCalledTimes(2);- expect(mockSendComponentValues.mock.lastCall?.[0]).toMatchInlineSnapshot(`- [- {- "objectId": "uiElementOne",- "value": "10",- },- {- "objectId": "uiElementTwo",- "value": "20",- },- ]- `);- });});diff --git a/frontend/src/core/kernel/handlers.ts b/frontend/src/core/kernel/handlers.tsindex 2f815e52cc..71f28d6108 100644--- a/frontend/src/core/kernel/handlers.ts+++ b/frontend/src/core/kernel/handlers.ts@@ -4,7 +4,6 @@ import { Objects } from "@/utils/objects";import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";import { LayoutData, LayoutState, initialLayoutState } from "../layout/layout";import { sendInstantiate } from "../network/requests";-import { RuntimeState } from "./RuntimeState";import { CellMessage, OperationMessage } from "./messages";import { LayoutType } from "@/components/editor/renderers/types";import { AppConfig } from "../config/config-schema";@@ -103,9 +102,7 @@ export function handleKernelReady(// Send the instantiate messageif (autoInstantiate) {// Start the run- RuntimeState.INSTANCE.registerRunStart();sendInstantiate({ objectIds, values }).catch((error) => {- RuntimeState.INSTANCE.registerRunEnd();onError(new Error("Failed to instantiate", { cause: error }));});}@@ -122,19 +119,6 @@ export function handleRemoveUIElements(VirtualFileTracker.INSTANCE.removeForCellId(cell_id);}-export function handleInterrupted() {- if (!RuntimeState.INSTANCE.running()) {- RuntimeState.INSTANCE.flushUpdates();- }-}--export function handleCompletedRun() {- RuntimeState.INSTANCE.registerRunEnd();- if (!RuntimeState.INSTANCE.running()) {- RuntimeState.INSTANCE.flushUpdates();- }-}-export function handleCellOperation(data: OperationMessageData<"cell-op">["data"],handleCellMessage: (message: CellMessage) => void,diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.tsindex 41e3af4b88..40584034b4 100644--- a/frontend/src/core/pyodide/bridge.ts+++ b/frontend/src/core/pyodide/bridge.ts@@ -38,12 +38,14 @@ import { PyodideRouter } from "./router";import { getMarimoVersion } from "../dom/marimo-tag";import { getWorkerRPC } from "./rpc";import { API } from "../network/api";-import { RuntimeState } from "@/core/kernel/RuntimeState";import { parseUserConfig } from "../config/config-schema";import { throwNotImplemented } from "@/utils/functions";import type { WorkerSchema } from "./worker/worker";import type { SaveWorkerSchema } from "./worker/save-worker";import { toast } from "@/components/ui/use-toast";+import { generateUUID } from "@/utils/uuid";+import { store } from "../state/jotai";+import { notebookIsRunningAtom } from "../cells/cells";export class PyodideBridge implements RunRequests, EditRequests {static INSTANCE = new PyodideBridge();@@ -236,7 +238,8 @@ export class PyodideBridge implements RunRequests, EditRequests {// Because the Pyodide worker is single-threaded, sending// code completion requests while the kernel is running is useless// and runs the risk of choking the kernel- if (!RuntimeState.INSTANCE.running()) {+ const isRunning = store.get(notebookIsRunningAtom);+ if (!isRunning) {await this.rpc.proxy.request.bridge({functionName: "code_complete",payload: request,@@ -321,6 +324,7 @@ export class PyodideBridge implements RunRequests, EditRequests {update.objectId,update.value,]),+ token: generateUUID(),});return null;};diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex cf0f82712c..1c7d862429 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -27,8 +27,6 @@ import { createWsUrl } from "./createWsUrl";import { useSetAppConfig } from "../config/config";import {handleCellOperation,- handleCompletedRun,- handleInterrupted,handleKernelReady,handleRemoveUIElements,} from "../kernel/handlers";@@ -73,10 +71,8 @@ export function useMarimoWebSocket(opts: {return;case "completed-run":- handleCompletedRun();return;case "interrupted":- handleInterrupted();return;case "remove-ui-elements":diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.pyindex 56f5026742..517624424c 100644--- a/marimo/_pyodide/bootstrap.py+++ b/marimo/_pyodide/bootstrap.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotationsimport jsondiff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 0404cfe3de..c95b6dfa96 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -26,8 +26,12 @@ from marimo._runtime.requests import (AppMetadata,CompletionRequest,ControlRequest,+ SetUIElementValueRequest,)from marimo._runtime.runtime import Kernel+from marimo._runtime.utils.set_ui_element_request_manager import (+ SetUIElementRequestManager,+)from marimo._server.export.exporter import Exporterfrom marimo._server.file_manager import AppFileManagerfrom marimo._server.files.os_file_system import OSFileSystem@@ -70,6 +74,11 @@ class AsyncQueueManager:# ) are sent through the control queueself.control_queue = asyncio.Queue[requests.ControlRequest]()+ # set UI elements duplicated in another queue so they can be batched+ self.set_ui_element_queue = asyncio.Queue[+ requests.SetUIElementValueRequest+ ]()+# Code completion requests are sent through a separate queueself.completion_queue = asyncio.Queue[requests.CompletionRequest]()@@ -115,6 +124,7 @@ class PyodideSession:async def start(self) -> None:self.kernel_task = launch_pyodide_kernel(control_queue=self._queue_manager.control_queue,+ set_ui_element_queue=self._queue_manager.set_ui_element_queue,completion_queue=self._queue_manager.completion_queue,input_queue=self._queue_manager.input_queue,on_message=self._on_message,@@ -127,6 +137,8 @@ class PyodideSession:def put_control_request(self, request: requests.ControlRequest) -> None:self._queue_manager.control_queue.put_nowait(request)+ if isinstance(request, requests.SetUIElementValueRequest):+ self._queue_manager.set_ui_element_queue.put_nowait(request)def put_completion_request(self, request: requests.CompletionRequest@@ -287,6 +299,7 @@ class PyodideBridge:def launch_pyodide_kernel(control_queue: asyncio.Queue[ControlRequest],+ set_ui_element_queue: asyncio.Queue[SetUIElementValueRequest],completion_queue: asyncio.Queue[CompletionRequest],input_queue: asyncio.Queue[str],on_message: Callable[[KernelMessage], None],@@ -340,11 +353,17 @@ def launch_pyodide_kernel(signal.SIGINT, handlers.construct_interrupt_handler(kernel))+ ui_element_request_mgr = SetUIElementRequestManager(set_ui_element_queue)+async def listen_messages() -> None:while True:- request = await control_queue.get()+ request: ControlRequest | None = await control_queue.get()LOGGER.debug("received request %s", request)- await kernel.handle_message(request)+ if isinstance(request, requests.SetUIElementValueRequest):+ request = ui_element_request_mgr.process_request(request)++ if request is not None:+ await kernel.handle_message(request)async def listen_completion() -> None:while True:diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 676614a123..27cb3216de 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -1,8 +1,9 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Any, Dict, List, Optional, Tuple, TypeVar, Union+from uuid import uuid4from marimo._ast.cell import CellId_tfrom marimo._config.config import MarimoConfig@@ -37,6 +38,8 @@ class ExecuteMultipleRequest:class SetUIElementValueRequest:# (object id, value) tuplesids_and_values: List[Tuple[UIElementId, Any]]+ # uniquely identifies the request+ token: str = field(default_factory=lambda: str(uuid4()))@dataclassdiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 8d28ee5b1d..5f4e79a61c 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -100,6 +100,9 @@ from marimo._runtime.runner.hooks import (PREPARATION_HOOKS,)from marimo._runtime.state import State+from marimo._runtime.utils.set_ui_element_request_manager import (+ SetUIElementRequestManager,+)from marimo._runtime.validate_graph import check_for_errorsfrom marimo._runtime.win32_interrupt_handler import Win32InterruptHandlerfrom marimo._server.types import QueueType@@ -1307,6 +1310,7 @@ class Kernel:def launch_kernel(control_queue: QueueType[ControlRequest],+ set_ui_element_queue: QueueType[SetUIElementValueRequest],completion_queue: QueueType[CompletionRequest],input_queue: QueueType[str],socket_addr: tuple[str, int],@@ -1407,10 +1411,12 @@ def launch_kernel(signal.SIGTERM, handlers.construct_sigterm_handler(kernel))+ ui_element_request_mgr = SetUIElementRequestManager(set_ui_element_queue)+async def control_loop() -> None:while True:try:- request = control_queue.get()+ request: ControlRequest | None = control_queue.get()except Exception as e:# triggered on Windows when quit with Ctrl+CLOGGER.debug("kernel queue.get() failed %s", e)@@ -1418,7 +1424,11 @@ def launch_kernel(LOGGER.debug("received request %s", request)if isinstance(request, StopRequest):break- await kernel.handle_message(request)+ elif isinstance(request, SetUIElementValueRequest):+ request = ui_element_request_mgr.process_request(request)++ if request is not None:+ await kernel.handle_message(request)# The control loop is asynchronous only because we allow user code to use# top-level await; nothing else is awaited. Don't introduce asyncdiff --git a/marimo/_runtime/utils/set_ui_element_request_manager.py b/marimo/_runtime/utils/set_ui_element_request_manager.pynew file mode 100644index 0000000000..e5e95a6b33--- /dev/null+++ b/marimo/_runtime/utils/set_ui_element_request_manager.py@@ -0,0 +1,57 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING, Any++from marimo._plugins.ui._core.registry import UIElementId+from marimo._runtime.requests import SetUIElementValueRequest+from marimo._server.types import QueueType++if TYPE_CHECKING:+ import asyncio+++class SetUIElementRequestManager:+ def __init__(+ self,+ set_ui_element_queue: QueueType[SetUIElementValueRequest]+ | asyncio.Queue[SetUIElementValueRequest],+ ) -> None:+ self._set_ui_element_queue = set_ui_element_queue+ self._processed_request_tokens: set[str] = set()++ def process_request(+ self, request: SetUIElementValueRequest+ ) -> SetUIElementValueRequest | None:+ request_batch: list[SetUIElementValueRequest] = []+ if request.token not in self._processed_request_tokens:+ request_batch.append(request)+ self._processed_request_tokens.add(request.token)+ else:+ self._processed_request_tokens.remove(request.token)++ while not self._set_ui_element_queue.empty():+ r = self._set_ui_element_queue.get_nowait()+ if r.token not in self._processed_request_tokens:+ request_batch.append(r)+ self._processed_request_tokens.add(r.token)+ else:+ self._processed_request_tokens.remove(r.token)++ return self._merge_set_ui_element_requests(request_batch)++ def _merge_set_ui_element_requests(+ self,+ requests: list[SetUIElementValueRequest],+ ) -> SetUIElementValueRequest | None:+ if not requests:+ return None++ merged: dict[UIElementId, Any] = {}+ for request in requests:+ for ui_id, value in request.ids_and_values:+ merged[ui_id] = value+ return SetUIElementValueRequest(+ ids_and_values=[(ui_id, value) for ui_id, value in merged.items()],+ token="",+ )diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.pyindex 0d5acf9e8a..0ad7098076 100644--- a/marimo/_server/api/endpoints/execution.py+++ b/marimo/_server/api/endpoints/execution.py@@ -2,6 +2,7 @@from __future__ import annotationsfrom typing import TYPE_CHECKING+from uuid import uuid4from starlette.authentication import requires@@ -42,8 +43,9 @@ async def set_ui_element_values(app_state = AppState(request)body = await parse_request(request, cls=UpdateComponentValuesRequest)app_state.require_current_session().put_control_request(- SetUIElementValueRequest(body.zip())+ SetUIElementValueRequest(body.zip(), token=str(uuid4())))+return SuccessResponse()diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 2468eda200..985aa58084 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -26,6 +26,7 @@ from multiprocessing import connectionfrom multiprocessing.queues import Queue as MPQueuefrom pathlib import Pathfrom typing import Any, Optional+from uuid import uuid4from marimo import _loggersfrom marimo._ast.cell import CellConfig, CellId_t@@ -83,6 +84,13 @@ class QueueManager:context.Queue() if context is not None else queue.Queue())+ # Set UI element queues are stored in both the control queue and+ # this queue, so that the backend can merge/batch set-ui-element+ # requests.+ self.set_ui_element_queue: QueueType[+ requests.SetUIElementValueRequest+ ] = context.Queue() if context is not None else queue.Queue()+# Code completion requests are sent through a separate queueself.completion_queue: QueueType[requests.CompletionRequest] = (context.Queue() if context is not None else queue.Queue()@@ -116,6 +124,10 @@ class QueueManager:# exit; we don't join the thread because we don't want to blockself.control_queue.put(requests.StopRequest())+ if isinstance(self.set_ui_element_queue, MPQueue):+ self.set_ui_element_queue.cancel_join_thread()+ self.set_ui_element_queue.close()+if isinstance(self.input_queue, MPQueue):# again, don't make the child process wait for the queues to emptyself.input_queue.cancel_join_thread()@@ -162,6 +174,7 @@ class KernelManager:target=runtime.launch_kernel,args=(self.queue_manager.control_queue,+ self.queue_manager.set_ui_element_queue,self.queue_manager.completion_queue,self.queue_manager.input_queue,listener.address,@@ -200,6 +213,7 @@ class KernelManager:target=launch_kernel_with_cleanup,args=(self.queue_manager.control_queue,+ self.queue_manager.set_ui_element_queue,self.queue_manager.completion_queue,self.queue_manager.input_queue,listener.address,@@ -343,6 +357,8 @@ class Session:def put_control_request(self, request: requests.ControlRequest) -> None:self._queue_manager.control_queue.put(request)+ if isinstance(request, SetUIElementValueRequest):+ self._queue_manager.set_ui_element_queue.put(request)self.session_view.add_control_request(request)def put_completion_request(@@ -414,7 +430,7 @@ class Session:CreationRequest(execution_requests=execution_requests,set_ui_element_value_request=SetUIElementValueRequest(- request.zip(),+ request.zip(), token=str(uuid4())),))diff --git a/marimo/_smoke_tests/bugs/1362.py b/marimo/_smoke_tests/bugs/1362.pyindex 1f997c8938..84b5e3f909 100644--- a/marimo/_smoke_tests/bugs/1362.py+++ b/marimo/_smoke_tests/bugs/1362.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.5.2"