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 UI element updates not working in WASM due to request parsing order (#6354)

Trevor Manz4d3e1dec5177
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index df93f5188f..11d40fb015 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -204,6 +204,38 @@ class PyodideSession:
T = TypeVar("T")
+def parse_wasm_control_request(request: str) -> requests.ControlRequest:
+ """Parse a control request string for WASM/Pyodide.
+
+ This iterates through ControlRequest types in order until one successfully
+ parses. The order matters because some types have overlapping structures
+ when parsed with msgspec (e.g., types with only optional fields).
+
+ Args:
+ request: JSON string containing the request
+
+ Returns:
+ Parsed ControlRequest
+
+ Raises:
+ msgspec.DecodeError: If no type successfully parses
+ """
+ parsed: typing.Union[requests.ControlRequest, None] = None
+ for ControlRequestType in typing.get_args(requests.ControlRequest):
+ try:
+ parsed = parse_raw(request, cls=ControlRequestType)
+ break # success
+ except msgspec.DecodeError:
+ continue
+
+ if parsed is None:
+ raise msgspec.DecodeError(
+ f"Could not decode ControlRequest as any of {typing.get_args(requests.ControlRequest)}"
+ )
+
+ return parsed
+
+
class PyodideBridge:
def __init__(
self,
@@ -213,21 +245,7 @@ class PyodideBridge:
self.file_system = OSFileSystem()
def put_control_request(self, request: str) -> None:
- # Hack: msgspec only supports discriminated unions. This is a hack to just
- # iterate through possible ControlRequest variants and decode until one works.
- parsed = None
- for ControlRequestType in typing.get_args(requests.ControlRequest):
- try:
- parsed = parse_raw(request, cls=ControlRequestType)
- break # success
- except msgspec.DecodeError:
- continue
-
- if parsed is None:
- raise msgspec.DecodeError(
- f"Could not decode ControlRequest as any of {typing.get_args(requests.ControlRequest)}"
- )
-
+ parsed = parse_wasm_control_request(request)
self.session.put_control_request(parsed)
def put_input(self, text: str) -> None:
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index b5ca61ef08..31a853c8f2 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -357,25 +357,48 @@ class RefreshSecretsRequest(msgspec.Struct, rename="camel"):
pass
+# IMPORTANT: This is NOT a discriminated union. In WASM/Pyodide, we parse requests
+# by trying each type in order until one succeeds (see PyodideBridge.put_control_request).
+# The order matters because some types have overlapping structures when parsed with
+# msgspec (e.g., types with only optional fields).
+#
+# Ordering principles for WASM compatibility:
+# 1. Types with more specific/required fields should come before generic ones
+# 2. Types with unique field names should come before types with common field names
+# 3. Types with no fields or only optional fields should come last
+#
+# Known overlaps to be careful about:
+# - SetUIElementValueRequest has specific fields (object_ids, values) and should
+# come before generic requests
+# - ExecuteStaleRequest has only an optional 'request' field and could match many
+# payloads - should be near the end
+# - StopRequest and RefreshSecretsRequest have no fields and will match any empty
+# object - should be last
ControlRequest = Union[
+ # Requests with many specific required fields (most specific first)
CreationRequest,
- DeleteCellRequest,
ExecuteMultipleRequest,
- ExecuteScratchpadRequest,
- ExecuteStaleRequest,
- FunctionCallRequest,
InstallMissingPackagesRequest,
- ListSecretKeysRequest,
- PdbRequest,
PreviewDatasetColumnRequest,
- PreviewSQLTableListRequest,
- PreviewDataSourceConnectionRequest,
PreviewSQLTableRequest,
- RefreshSecretsRequest,
- RenameRequest,
- SetCellConfigRequest,
+ PreviewSQLTableListRequest,
SetUIElementValueRequest,
SetModelMessageRequest,
+ FunctionCallRequest,
+ # Requests with fewer but still specific required fields
+ # Note: DeleteCellRequest and PdbRequest both have only cellId as required field.
+ # We put DeleteCellRequest first as it's more commonly used in WASM.
+ # PdbRequest (debugger) is rarely/never used in WASM context.
+ DeleteCellRequest,
+ PdbRequest,
+ ExecuteScratchpadRequest,
+ RenameRequest,
+ SetCellConfigRequest,
SetUserConfigRequest,
+ ListSecretKeysRequest,
+ PreviewDataSourceConnectionRequest,
+ # Requests with no fields (will match any empty object)
StopRequest,
+ RefreshSecretsRequest,
+ ExecuteStaleRequest, # only comes from backend set low priority
]
diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.py
index 97b5cb2ba2..46789e4f88 100644
--- a/tests/_pyodide/test_pyodide_session.py
+++ b/tests/_pyodide/test_pyodide_session.py
@@ -11,11 +11,22 @@ import pytest
from marimo._ast.app_config import _AppConfig
from marimo._config.config import DEFAULT_CONFIG
from marimo._messaging.types import KernelMessage
-from marimo._pyodide.pyodide_session import AsyncQueueManager, PyodideSession
+from marimo._pyodide.pyodide_session import (
+ AsyncQueueManager,
+ PyodideSession,
+ parse_wasm_control_request,
+)
from marimo._runtime.context.types import teardown_context
from marimo._runtime.requests import (
AppMetadata,
+ CreationRequest,
+ DeleteCellRequest,
ExecuteMultipleRequest,
+ ExecuteScratchpadRequest,
+ InstallMissingPackagesRequest,
+ ListSecretKeysRequest,
+ RenameRequest,
+ SetCellConfigRequest,
SetUIElementValueRequest,
StopRequest,
)
@@ -215,3 +226,60 @@ async def test_pyodide_session_put_input(
assert not pyodide_session._queue_manager.input_queue.empty()
assert await pyodide_session._queue_manager.input_queue.get() == input_text
+
+
+ ("json_payload", "expected_type"),
+ [
+ # Most specific requests with many required fields
+ (
+ '{"executionRequests": [{"cellId": "cell-1", "code": "print(1)"}], '
+ '"setUiElementValueRequest": {"objectIds": [], "values": []}, '
+ '"autoRun": true}',
+ CreationRequest,
+ ),
+ (
+ '{"cellIds": ["cell-1"], "codes": ["print(1)"]}',
+ ExecuteMultipleRequest,
+ ),
+ (
+ '{"manager": "pip", "packages": ["numpy"], "versions": {}}',
+ InstallMissingPackagesRequest,
+ ),
+ # SetUIElementValueRequest - has specific fields
+ (
+ '{"objectIds": ["test-1"], "values": [42], "token": "test-token"}',
+ SetUIElementValueRequest,
+ ),
+ (
+ '{"objectIds": ["test-1"], "values": [42]}', # Without token
+ SetUIElementValueRequest,
+ ),
+ # Requests with single required fields
+ # DeleteCellRequest comes before PdbRequest
+ # Note: Can't test PdbRequest since DeleteCellRequest will always match first
+ ('{"cellId": "cell-1"}', DeleteCellRequest),
+ ('{"code": "print(1)"}', ExecuteScratchpadRequest),
+ ('{"filename": "test.py"}', RenameRequest),
+ ('{"configs": {"cell-1": {"hide_code": true}}}', SetCellConfigRequest),
+ ('{"requestId": "req-1"}', ListSecretKeysRequest),
+ # Empty objects - StopRequest matches first among the empty requests
+ # Note: Can't test RefreshSecretsRequest since StopRequest will always match first
+ ("{}", StopRequest),
+ ],
+)
+def test_control_request_parsing_order(
+ json_payload: str, expected_type: type
+) -> None:
+ """Test that ControlRequest types are parsed in the correct order.
+
+ This is critical for WASM/Pyodide where we iterate through types until
+ one successfully parses. Types with overlapping structures must be
+ ordered correctly.
+ """
+
+ parsed = parse_wasm_control_request(json_payload)
+ assert type(parsed) is expected_type, (
+ f"Expected {expected_type.__name__} but got {type(parsed).__name__} "
+ f"for payload: {json_payload}"
+ )