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: don't block on background tasks created in cells (#4858)

Myles Scolnick383e6c3cb259
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index b5925c5cd5..c4b8c5c0c0 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -2716,9 +2716,22 @@ def launch_kernel(
ui_element_request_mgr = SetUIElementRequestManager(set_ui_element_queue)
async def control_loop(kernel: Kernel) -> None:
+ from queue import Empty
+
while True:
try:
- request: ControlRequest | None = control_queue.get()
+ TIMEOUT_S = 0.1
+ # 100ms timeout to avoid blocking
+ # this does not mean ControlRequest will be blocked for 100ms
+ # but rather background tasks may not start until 100ms have passed
+ request: ControlRequest | None = control_queue.get(
+ timeout=TIMEOUT_S
+ )
+ except Empty:
+ # Yield control back to the event loop to give
+ # other tasks a chance to run
+ await asyncio.sleep(0)
+ continue
except Exception as e:
# triggered on Windows when quit with Ctrl+C
LOGGER.debug("kernel queue.get() failed %s", e)
diff --git a/marimo/_smoke_tests/async/background_tasks.py b/marimo/_smoke_tests/async/background_tasks.py
new file mode 100644
index 0000000000..8f6238accf
--- /dev/null
+++ b/marimo/_smoke_tests/async/background_tasks.py
@@ -0,0 +1,49 @@
+import marimo
+
+__generated_with = "0.13.6"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def _():
+ import time
+ import asyncio
+
+
+ async def background_task(name, seconds):
+ """A simple task that prints messages at intervals."""
+ print(f"Task {name} started")
+ for i in range(seconds):
+ print(f"Task {name}: working... ({i + 1}/{seconds})")
+ await asyncio.sleep(1)
+ print(f"Task {name} completed")
+ return f"{name} result"
+ return asyncio, background_task
+
+
+def _(asyncio, background_task):
+ # Run this cell for a new background task
+ a = asyncio.create_task(background_task("A", 2))
+ return
+
+
+def _(asyncio, refresh):
+ # This list should have at least one task (the kernel). When creating tasks above, they should be added and then removed.
+ refresh
+ list(asyncio.all_tasks())
+ return
+
+
[email protected](hide_code=True)
+def _():
+ import marimo as mo
+
+ refresh = mo.ui.refresh(options=["1s"], default_interval="1s")
+ refresh
+ return (refresh,)
+
+
+if __name__ == "__main__":
+ app.run()