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: thread-safe redirection of console outputs in run mode (#8353)

Akshay Agrawalee5ccad88453
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.py
index b49511dfe2..b029c4c2d3 100644
--- a/marimo/_messaging/streams.py
+++ b/marimo/_messaging/streams.py
@@ -167,6 +167,22 @@ def _forward_os_stream(
...
+class _NoOpWatcher:
+ """A dummy watcher that does nothing, used when fd redirection is off."""
+
+ def start(self) -> None:
+ pass
+
+ def pause(self) -> None:
+ pass
+
+ def stop(self) -> None:
+ pass
+
+
+_NOOP_WATCHER = _NoOpWatcher()
+
+
class Watcher:
"""Watches and redirects a standard stream."""
@@ -213,10 +229,14 @@ class ThreadSafeStdout(Stdout):
errors = sys.stdout.errors
_fileno: int | None = None
- def __init__(self, stream: ThreadSafeStream):
+ def __init__(
+ self, stream: ThreadSafeStream, forward_os_streams: bool = True
+ ):
self._stream = stream
self._original_fd = sys.stdout.fileno()
- self._watcher = Watcher(self)
+ self._watcher: Watcher | _NoOpWatcher = (
+ Watcher(self) if forward_os_streams else _NOOP_WATCHER
+ )
def _stop(self) -> None:
self._watcher.stop()
@@ -279,10 +299,14 @@ class ThreadSafeStderr(Stderr):
errors = sys.stderr.errors
_fileno: int | None = None
- def __init__(self, stream: ThreadSafeStream):
+ def __init__(
+ self, stream: ThreadSafeStream, forward_os_streams: bool = True
+ ):
self._stream = stream
self._original_fd = sys.stderr.fileno()
- self._watcher = Watcher(self)
+ self._watcher: Watcher | _NoOpWatcher = (
+ Watcher(self) if forward_os_streams else _NOOP_WATCHER
+ )
def _stop(self) -> None:
self._watcher.stop()
@@ -415,13 +439,9 @@ class ThreadSafeStdin(Stdin):
def redirect(standard_stream: Stdout | Stderr) -> Iterator[None]:
"""Redirect a standard stream to the frontend."""
try:
- if isinstance(standard_stream, ThreadSafeStdout) or isinstance(
- standard_stream, ThreadSafeStderr
- ):
+ if isinstance(standard_stream, (ThreadSafeStdout, ThreadSafeStderr)):
standard_stream._watcher.start()
yield
finally:
- if isinstance(standard_stream, ThreadSafeStdout) or isinstance(
- standard_stream, ThreadSafeStderr
- ):
+ if isinstance(standard_stream, (ThreadSafeStdout, ThreadSafeStderr)):
standard_stream._watcher.pause()
diff --git a/marimo/_messaging/thread_local_streams.py b/marimo/_messaging/thread_local_streams.py
new file mode 100644
index 0000000000..8e08e738a5
--- /dev/null
+++ b/marimo/_messaging/thread_local_streams.py
@@ -0,0 +1,149 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Thread-local stream proxy for run mode.
+
+In run mode, multiple sessions share the same process. Each session runs in its
+own thread and needs sys.stdout / sys.stderr to route output to that session's
+frontend connection.
+
+ThreadLocalStreamProxy wraps the real sys.stdout / sys.stderr once at process
+level and dispatches writes to a per-thread stream registered via
+set_thread_local_streams().
+"""
+
+from __future__ import annotations
+
+import io
+import sys
+import threading
+from typing import TYPE_CHECKING, TextIO, Union
+
+from marimo._messaging.types import Stderr, Stdout
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+
+_proxies_installed = False
+_install_lock = threading.Lock()
+_original_stdout: TextIO | None = None
+_original_stderr: TextIO | None = None
+
+
+class ThreadLocalStreamProxy(io.TextIOBase):
+ """A proxy that dispatches writes to a per-thread stream.
+
+ When a thread has registered a stream via set_thread_local_streams(),
+ writes go there; otherwise they fall through to the original stream
+ (real sys.stdout / sys.stderr).
+ """
+
+ def __init__(
+ self, original: Union[io.TextIOBase, TextIO], name: str
+ ) -> None:
+ self._original = original
+ self._local = threading.local()
+ self._name = name
+ # Expose the underlying binary buffer so that code writing to
+ # sys.stdout.buffer (e.g. package installation logging) keeps working.
+ self.buffer: io.BufferedIOBase | None = getattr(
+ original, "buffer", None
+ )
+
+ # -- per-thread registration -------------------------------------------
+
+ def _set_stream(self, stream: io.TextIOBase) -> None:
+ self._local.stream = stream
+
+ def _clear_stream(self) -> None:
+ self._local.stream = None
+
+ def _get_stream(self) -> Union[io.TextIOBase, TextIO]:
+ stream = getattr(self._local, "stream", None)
+ return stream if stream is not None else self._original
+
+ # -- TextIOBase interface ----------------------------------------------
+
+ @property
+ def name(self) -> str:
+ return self._name
+
+ @property
+ def encoding(self) -> str: # type: ignore[override]
+ return getattr(self._get_stream(), "encoding", "utf-8")
+
+ @property
+ def errors(self) -> str | None: # type: ignore[override]
+ return getattr(self._get_stream(), "errors", None)
+
+ def write(self, data: str) -> int:
+ return self._get_stream().write(data)
+
+ def writelines(self, lines: Iterable[str]) -> None: # type: ignore[override]
+ self._get_stream().writelines(lines)
+
+ def flush(self) -> None:
+ self._get_stream().flush()
+
+ def fileno(self) -> int:
+ return self._original.fileno()
+
+ def isatty(self) -> bool:
+ return self._original.isatty()
+
+ def readable(self) -> bool:
+ return False
+
+ def writable(self) -> bool:
+ return True
+
+ def seekable(self) -> bool:
+ return False
+
+
+def install_thread_local_proxies() -> None:
+ """Install thread-local proxies as sys.stdout / sys.stderr (idempotent).
+
+ Called once from the main server thread before kernel threads are spawned.
+ """
+ global _proxies_installed, _original_stdout, _original_stderr
+ with _install_lock:
+ if _proxies_installed:
+ return
+ _original_stdout = sys.stdout
+ _original_stderr = sys.stderr
+ sys.stdout = ThreadLocalStreamProxy(sys.stdout, "<stdout>") # type: ignore[assignment]
+ sys.stderr = ThreadLocalStreamProxy(sys.stderr, "<stderr>") # type: ignore[assignment]
+ _proxies_installed = True
+
+
+def uninstall_thread_local_proxies() -> None:
+ """Remove thread-local proxies, restoring the original streams."""
+ global _proxies_installed, _original_stdout, _original_stderr
+ with _install_lock:
+ if not _proxies_installed:
+ return
+ if _original_stdout is not None:
+ sys.stdout = _original_stdout # type: ignore[assignment]
+ if _original_stderr is not None:
+ sys.stderr = _original_stderr # type: ignore[assignment]
+ _original_stdout = None
+ _original_stderr = None
+ _proxies_installed = False
+
+
+def set_thread_local_streams(
+ stdout: Stdout | None, stderr: Stderr | None
+) -> None:
+ """Register per-thread streams (call from each session thread)."""
+ if isinstance(sys.stdout, ThreadLocalStreamProxy) and stdout is not None:
+ sys.stdout._set_stream(stdout) # type: ignore[union-attr]
+ if isinstance(sys.stderr, ThreadLocalStreamProxy) and stderr is not None:
+ sys.stderr._set_stream(stderr) # type: ignore[union-attr]
+
+
+def clear_thread_local_streams() -> None:
+ """Clear per-thread streams (call when a session thread exits)."""
+ if isinstance(sys.stdout, ThreadLocalStreamProxy):
+ sys.stdout._clear_stream() # type: ignore[union-attr]
+ if isinstance(sys.stderr, ThreadLocalStreamProxy):
+ sys.stderr._clear_stream() # type: ignore[union-attr]
diff --git a/marimo/_runtime/capture.py b/marimo/_runtime/capture.py
index e5f8b1355a..8f77e19127 100644
--- a/marimo/_runtime/capture.py
+++ b/marimo/_runtime/capture.py
@@ -6,6 +6,7 @@ import io
import sys
from typing import TYPE_CHECKING
+from marimo._messaging.thread_local_streams import ThreadLocalStreamProxy
from marimo._plugins.stateless.plain_text import plain_text
from marimo._runtime.output import _output
@@ -13,6 +14,10 @@ if TYPE_CHECKING:
from collections.abc import Iterator
+def _is_proxy(stream: object) -> bool:
+ return isinstance(stream, ThreadLocalStreamProxy)
+
+
@contextlib.contextmanager
def capture_stdout() -> Iterator[io.StringIO]:
"""Capture standard output.
@@ -27,8 +32,21 @@ def capture_stdout() -> Iterator[io.StringIO]:
output = buffer.getvalue()
```
"""
- with contextlib.redirect_stdout(io.StringIO()) as buffer:
- yield buffer
+ proxy = sys.stdout
+ if _is_proxy(proxy):
+ # Temporarily swap the thread-local stream to a StringIO so that
+ # writes from this thread are captured while other threads are
+ # unaffected.
+ buffer = io.StringIO()
+ old = proxy._get_stream() # type: ignore[union-attr]
+ proxy._set_stream(buffer) # type: ignore[union-attr]
+ try:
+ yield buffer
+ finally:
+ proxy._set_stream(old) # type: ignore[union-attr]
+ else:
+ with contextlib.redirect_stdout(io.StringIO()) as buffer:
+ yield buffer
@contextlib.contextmanager
@@ -44,14 +62,35 @@ def capture_stderr() -> Iterator[io.StringIO]:
output = buffer.getvalue()
```
"""
- with contextlib.redirect_stderr(io.StringIO()) as buffer:
- yield buffer
+ proxy = sys.stderr
+ if _is_proxy(proxy):
+ buffer = io.StringIO()
+ old = proxy._get_stream() # type: ignore[union-attr]
+ proxy._set_stream(buffer) # type: ignore[union-attr]
+ try:
+ yield buffer
+ finally:
+ proxy._set_stream(old) # type: ignore[union-attr]
+ else:
+ with contextlib.redirect_stderr(io.StringIO()) as buffer:
+ yield buffer
def _redirect(msg: str) -> None:
_output.append(plain_text(msg))
+class _RedirectStream(io.TextIOBase):
+ """A stream wrapper that sends writes to the cell output area."""
+
+ def write(self, data: str) -> int:
+ _redirect(data)
+ return len(data)
+
+ def writable(self) -> bool:
+ return True
+
+
@contextlib.contextmanager
def redirect_stdout() -> Iterator[None]:
"""Redirect stdout to a cell's output area.
@@ -64,12 +103,23 @@ def redirect_stdout() -> Iterator[None]:
print("World!")
```
"""
- old_stdout_write = sys.stdout.write
- sys.stdout.write = _redirect # type: ignore
- try:
- yield
- finally:
- sys.stdout.write = old_stdout_write # type: ignore
+ proxy = sys.stdout
+ if _is_proxy(proxy):
+ # Temporarily swap the thread-local stream to one that redirects
+ # writes to the cell output area, leaving other threads unaffected.
+ old = proxy._get_stream() # type: ignore[union-attr]
+ proxy._set_stream(_RedirectStream()) # type: ignore[union-attr]
+ try:
+ yield
+ finally:
+ proxy._set_stream(old) # type: ignore[union-attr]
+ else:
+ old_stdout_write = sys.stdout.write
+ sys.stdout.write = _redirect # type: ignore
+ try:
+ yield
+ finally:
+ sys.stdout.write = old_stdout_write # type: ignore
@contextlib.contextmanager
@@ -84,9 +134,18 @@ def redirect_stderr() -> Iterator[None]:
sys.stderr.write("World!")
```
"""
- old_stderr_write = sys.stderr.write
- sys.stderr.write = _redirect # type: ignore
- try:
- yield
- finally:
- sys.stderr.write = old_stderr_write # type: ignore
+ proxy = sys.stderr
+ if _is_proxy(proxy):
+ old = proxy._get_stream() # type: ignore[union-attr]
+ proxy._set_stream(_RedirectStream()) # type: ignore[union-attr]
+ try:
+ yield
+ finally:
+ proxy._set_stream(old) # type: ignore[union-attr]
+ else:
+ old_stderr_write = sys.stderr.write
+ sys.stderr.write = _redirect # type: ignore
+ try:
+ yield
+ finally:
+ sys.stderr.write = old_stderr_write # type: ignore
diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.py
index fda51ed390..08639cdb32 100644
--- a/marimo/_runtime/redirect_streams.py
+++ b/marimo/_runtime/redirect_streams.py
@@ -6,8 +6,11 @@ import os
import sys
from typing import TYPE_CHECKING
-from marimo._messaging.streams import (
- redirect,
+from marimo._messaging.streams import redirect
+from marimo._messaging.thread_local_streams import (
+ ThreadLocalStreamProxy,
+ clear_thread_local_streams,
+ set_thread_local_streams,
)
from marimo._messaging.types import Stderr, Stdin, Stdout, Stream
from marimo._types.ids import CellId_t
@@ -73,22 +76,33 @@ def redirect_streams(
stream.cell_id = cell_id_old
return
- # NB: Python doesn't allow monkey patching methods builtins, so
- # we replace these streams outright
- py_stdout = sys.stdout
- py_stderr = sys.stderr
- py_stdin = sys.stdin
- sys.stdout = stdout # type: ignore
- sys.stderr = stderr # type: ignore
- sys.stdin = stdin # type: ignore
-
- try:
- with redirect(stdout), redirect(stderr):
+ if isinstance(sys.stdout, ThreadLocalStreamProxy):
+ # In run mode with console redirection enabled, sys.stdout/sys.stderr
+ # are already patched to point to an object that forwards read/write.
+ #
+ # We don't support redirecting file descriptors in run mode.
+ # We also don't support sys.stdin redirection.
+ set_thread_local_streams(stdout, stderr)
+ try:
yield
- finally:
- # The redirect context manager relies on these being installed;
- # restore them after the context manager quits
- sys.stdout = py_stdout
- sys.stderr = py_stderr
- sys.stdin = py_stdin
- stream.cell_id = cell_id_old
+ finally:
+ clear_thread_local_streams()
+ stream.cell_id = cell_id_old
+ else:
+ # In edit mode, we have one process per notebook, so we can safely
+ # replace sys.stdout/sys.stderr and redirect OS streams
+ py_stdout = sys.stdout
+ py_stderr = sys.stderr
+ py_stdin = sys.stdin
+ sys.stdout = stdout # type: ignore
+ sys.stderr = stderr # type: ignore
+ sys.stdin = stdin # type: ignore
+
+ try:
+ with redirect(stdout), redirect(stderr):
+ yield
+ finally:
+ sys.stdout = py_stdout
+ sys.stderr = py_stderr
+ sys.stdin = py_stdin
+ stream.cell_id = cell_id_old
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index c6d168fae1..79279bf230 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -3177,6 +3177,10 @@ def launch_kernel(
profiler.enable()
should_redirect_stdio = is_edit_mode or redirect_console_to_browser
+ # Only use os.dup2-based fd redirection in process-based modes
+ # (edit mode / IPC). Thread-based run mode uses the lighter-weight
+ # thread-local proxy instead to avoid process-global fd mutations.
+ use_fd_redirect = is_subprocess
# Create communication channels
pipe: Optional[TypedConnection[KernelMessage]] = None
@@ -3212,10 +3216,16 @@ def launch_kernel(
"One of queue_pipe and socket_addr must be non None"
)
- # Console output is hidden in run mode, so no need to redirect
- # (redirection of console outputs is not thread-safe anyway)
- stdout = ThreadSafeStdout(stream) if should_redirect_stdio else None
- stderr = ThreadSafeStderr(stream) if should_redirect_stdio else None
+ stdout = (
+ ThreadSafeStdout(stream, forward_os_streams=use_fd_redirect)
+ if should_redirect_stdio
+ else None
+ )
+ stderr = (
+ ThreadSafeStderr(stream, forward_os_streams=use_fd_redirect)
+ if should_redirect_stdio
+ else None
+ )
# TODO(akshayka): stdin in run mode? input(prompt) uses stdout, which
# isn't currently available in run mode.
stdin = ThreadSafeStdin(stream) if is_edit_mode else None
@@ -3359,6 +3369,13 @@ def launch_kernel(
# reason; prefer using threads (for performance and clarity).
asyncio.run(control_loop(kernel))
+ if not use_fd_redirect:
+ from marimo._messaging.thread_local_streams import (
+ clear_thread_local_streams,
+ )
+
+ clear_thread_local_streams()
+
if profiler is not None and profile_path is not None:
profiler.disable()
profiler.dump_stats(profile_path)
diff --git a/marimo/_session/managers/kernel.py b/marimo/_session/managers/kernel.py
index 549ddcde63..8805ff96e5 100644
--- a/marimo/_session/managers/kernel.py
+++ b/marimo/_session/managers/kernel.py
@@ -113,6 +113,13 @@ class KernelManagerImpl(KernelManager):
# formatters ...)
register_formatters(theme=self.config_manager.theme)
+ if self.redirect_console_to_browser:
+ from marimo._messaging.thread_local_streams import (
+ install_thread_local_proxies,
+ )
+
+ install_thread_local_proxies()
+
assert self.queue_manager.stream_queue is not None
# Make threads daemons so killing the server immediately brings
# down all client sessions
diff --git a/tests/_messaging/test_thread_local_proxy.py b/tests/_messaging/test_thread_local_proxy.py
new file mode 100644
index 0000000000..95e60d09f3
--- /dev/null
+++ b/tests/_messaging/test_thread_local_proxy.py
@@ -0,0 +1,381 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Tests for ThreadLocalStreamProxy and thread-local stream helpers."""
+
+from __future__ import annotations
+
+import io
+import sys
+import threading
+from unittest.mock import MagicMock
+
+from marimo._messaging.thread_local_streams import (
+ ThreadLocalStreamProxy,
+ clear_thread_local_streams,
+ install_thread_local_proxies,
+ set_thread_local_streams,
+ uninstall_thread_local_proxies,
+)
+
+# ---------------------------------------------------------------------------
+# ThreadLocalStreamProxy unit tests
+# ---------------------------------------------------------------------------
+
+
+class TestThreadLocalStreamProxy:
+ def test_write_to_original_when_no_thread_local(self) -> None:
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+ proxy.write("hello")
+ assert original.getvalue() == "hello"
+
+ def test_write_to_thread_local_stream(self) -> None:
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+
+ thread_stream = io.StringIO()
+ proxy._set_stream(thread_stream)
+ proxy.write("hello")
+
+ assert thread_stream.getvalue() == "hello"
+ assert original.getvalue() == ""
+
+ def test_clear_falls_back_to_original(self) -> None:
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+
+ thread_stream = io.StringIO()
+ proxy._set_stream(thread_stream)
+ proxy.write("a")
+ proxy._clear_stream()
+ proxy.write("b")
+
+ assert thread_stream.getvalue() == "a"
+ assert original.getvalue() == "b"
+
+ def test_thread_isolation(self) -> None:
+ """Writes from different threads go to different streams."""
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+
+ stream_a = io.StringIO()
+ stream_b = io.StringIO()
+ barrier = threading.Barrier(2)
+
+ def thread_fn(stream: io.StringIO, label: str) -> None:
+ proxy._set_stream(stream)
+ barrier.wait() # synchronise so both threads are active
+ proxy.write(label)
+ proxy.flush()
+
+ t1 = threading.Thread(target=thread_fn, args=(stream_a, "A"))
+ t2 = threading.Thread(target=thread_fn, args=(stream_b, "B"))
+ t1.start()
+ t2.start()
+ t1.join()
+ t2.join()
+
+ assert stream_a.getvalue() == "A"
+ assert stream_b.getvalue() == "B"
+ assert original.getvalue() == ""
+
+ def test_unregistered_thread_uses_original(self) -> None:
+ """Threads that never call _set_stream write to original."""
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+
+ def thread_fn() -> None:
+ proxy.write("unregistered")
+
+ t = threading.Thread(target=thread_fn)
+ t.start()
+ t.join()
+
+ assert original.getvalue() == "unregistered"
+
+ def test_writelines(self) -> None:
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+ proxy.writelines(["hello", " ", "world"])
+ assert original.getvalue() == "hello world"
+
+ def test_flush_delegates(self) -> None:
+ original = MagicMock(spec=io.StringIO)
+ original.flush = MagicMock()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+ proxy.flush()
+ original.flush.assert_called_once()
+
+ def test_name_property(self) -> None:
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+ assert proxy.name == "<stdout>"
+
+ def test_writable(self) -> None:
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+ assert proxy.writable()
+ assert not proxy.readable()
+ assert not proxy.seekable()
+
+ def test_buffer_attribute_from_real_stdout(self) -> None:
+ """Proxy exposes .buffer from the original stream."""
+ proxy = ThreadLocalStreamProxy(sys.__stdout__, "<stdout>")
+ assert proxy.buffer is sys.__stdout__.buffer # type: ignore[union-attr]
+
+ def test_buffer_attribute_none_for_stringio(self) -> None:
+ """StringIO has no buffer, so proxy.buffer should be None."""
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+ assert proxy.buffer is None
+
+
+# ---------------------------------------------------------------------------
+# install / set / clear helper tests
+# ---------------------------------------------------------------------------
+
+
+class TestHelperFunctions:
+ def test_install_thread_local_proxies_is_idempotent(self) -> None:
+ """install_thread_local_proxies installs proxies and is idempotent."""
+ try:
+ install_thread_local_proxies()
+ first_stdout = sys.stdout
+ first_stderr = sys.stderr
+ assert isinstance(first_stdout, ThreadLocalStreamProxy)
+ assert isinstance(first_stderr, ThreadLocalStreamProxy)
+
+ # Second call should be a no-op
+ install_thread_local_proxies()
+ assert sys.stdout is first_stdout
+ assert sys.stderr is first_stderr
+ finally:
+ uninstall_thread_local_proxies()
+
+ def test_set_and_clear_thread_local_streams(self) -> None:
+ """set/clear thread local streams operate on proxies."""
+ saved_stdout = sys.stdout
+ saved_stderr = sys.stderr
+ try:
+ install_thread_local_proxies()
+
+ mock_out = MagicMock()
+ mock_err = MagicMock()
+ set_thread_local_streams(mock_out, mock_err)
+
+ proxy_out: ThreadLocalStreamProxy = sys.stdout # type: ignore
+ proxy_err: ThreadLocalStreamProxy = sys.stderr # type: ignore
+ assert proxy_out._get_stream() is mock_out
+ assert proxy_err._get_stream() is mock_err
+
+ clear_thread_local_streams()
+ # After clear, should fall back to original
+ assert proxy_out._get_stream() is saved_stdout
+ assert proxy_err._get_stream() is saved_stderr
+ finally:
+ uninstall_thread_local_proxies()
+
+ def test_uninstall_restores_originals_even_if_stdout_replaced(
+ self,
+ ) -> None:
+ """uninstall restores originals even if sys.stdout was overwritten."""
+ saved_stdout = sys.stdout
+ saved_stderr = sys.stderr
+ try:
+ install_thread_local_proxies()
+ # Something replaces sys.stdout after install
+ sys.stdout = io.StringIO() # type: ignore
+ sys.stderr = io.StringIO() # type: ignore
+ # uninstall should still restore the real originals
+ uninstall_thread_local_proxies()
+ assert sys.stdout is saved_stdout
+ assert sys.stderr is saved_stderr
+ finally:
+ sys.stdout = saved_stdout
+ sys.stderr = saved_stderr
+
+ def test_set_noop_without_proxy(self) -> None:
+ """set/clear are safe to call when proxies are not installed."""
+ saved_stdout = sys.stdout
+ saved_stderr = sys.stderr
+ try:
+ sys.stdout = io.StringIO() # type: ignore
+ sys.stderr = io.StringIO() # type: ignore
+ # Should not raise
+ set_thread_local_streams(MagicMock(), MagicMock())
+ clear_thread_local_streams()
+ finally:
+ sys.stdout = saved_stdout
+ sys.stderr = saved_stderr
+
+
+# ---------------------------------------------------------------------------
+# capture / redirect with proxies installed
+# ---------------------------------------------------------------------------
+
+
+class TestCaptureWithProxy:
+ """Tests for capture_stdout / capture_stderr when proxies are active."""
+
+ def test_capture_stdout_with_proxy(self) -> None:
+ from marimo._runtime.capture import capture_stdout
+
+ saved_stdout = sys.stdout
+ try:
+ install_thread_local_proxies()
+ proxy: ThreadLocalStreamProxy = sys.stdout # type: ignore
+
+ session_stream = io.StringIO()
+ proxy._set_stream(session_stream)
+
+ with capture_stdout() as buf:
+ sys.stdout.write("captured")
+
+ # Writes inside the context should go to the buffer
+ assert buf.getvalue() == "captured"
+ # The session stream should not see captured output
+ assert session_stream.getvalue() == ""
+ # After exiting, writes should resume going to session stream
+ sys.stdout.write("after")
+ assert session_stream.getvalue() == "after"
+ finally:
+ sys.stdout = saved_stdout
+ uninstall_thread_local_proxies()
+
+ def test_capture_stderr_with_proxy(self) -> None:
+ from marimo._runtime.capture import capture_stderr
+
+ saved_stderr = sys.stderr
+ try:
+ install_thread_local_proxies()
+ proxy: ThreadLocalStreamProxy = sys.stderr # type: ignore
+
+ session_stream = io.StringIO()
+ proxy._set_stream(session_stream)
+
+ with capture_stderr() as buf:
+ sys.stderr.write("captured")
+
+ assert buf.getvalue() == "captured"
+ assert session_stream.getvalue() == ""
+ sys.stderr.write("after")
+ assert session_stream.getvalue() == "after"
+ finally:
+ sys.stderr = saved_stderr
+ uninstall_thread_local_proxies()
+
+ def test_redirect_stdout_with_proxy(self) -> None:
+ from marimo._runtime.capture import redirect_stdout
+
+ saved_stdout = sys.stdout
+ try:
+ install_thread_local_proxies()
+ proxy: ThreadLocalStreamProxy = sys.stdout # type: ignore
+
+ session_stream = io.StringIO()
+ proxy._set_stream(session_stream)
+
+ with redirect_stdout():
+ # Writes should go to _output (via _redirect), not session
+ sys.stdout.write("redirected")
+
+ # Session stream should not see redirected writes
+ assert session_stream.getvalue() == ""
+ # After exiting, writes should resume going to session stream
+ sys.stdout.write("after")
+ assert session_stream.getvalue() == "after"
+ finally:
+ sys.stdout = saved_stdout
+ uninstall_thread_local_proxies()
+
+ def test_redirect_stderr_with_proxy(self) -> None:
+ from marimo._runtime.capture import redirect_stderr
+
+ saved_stderr = sys.stderr
+ try:
+ install_thread_local_proxies()
+ proxy: ThreadLocalStreamProxy = sys.stderr # type: ignore
+
+ session_stream = io.StringIO()
+ proxy._set_stream(session_stream)
+
+ with redirect_stderr():
+ sys.stderr.write("redirected")
+
+ assert session_stream.getvalue() == ""
+ sys.stderr.write("after")
+ assert session_stream.getvalue() == "after"
+ finally:
+ sys.stderr = saved_stderr
+ uninstall_thread_local_proxies()
+
+ def test_capture_does_not_affect_other_threads(self) -> None:
+ """capture_stdout in one thread should not affect another thread."""
+ from marimo._runtime.capture import capture_stdout
+
+ saved_stdout = sys.stdout
+ try:
+ install_thread_local_proxies()
+ proxy: ThreadLocalStreamProxy = sys.stdout # type: ignore
+
+ other_stream = io.StringIO()
+ barrier = threading.Barrier(2)
+ captured: list[str] = []
+
+ def other_thread() -> None:
+ proxy._set_stream(other_stream)
+ barrier.wait()
+ proxy.write("other")
+
+ session_stream = io.StringIO()
+ proxy._set_stream(session_stream)
+
+ t = threading.Thread(target=other_thread)
+ t.start()
+ with capture_stdout() as buf:
+ barrier.wait()
+ sys.stdout.write("main")
+ t.join()
+ captured.append(buf.getvalue())
+
+ assert captured[0] == "main"
+ assert other_stream.getvalue() == "other"
+ finally:
+ sys.stdout = saved_stdout
+ uninstall_thread_local_proxies()
+
+
+# ---------------------------------------------------------------------------
+# Integration: multiple "sessions" in threads
+# ---------------------------------------------------------------------------
+
+
+def test_multi_session_no_deadlock() -> None:
+ """Simulate two sessions in threads — no deadlock, correct routing."""
+ original = io.StringIO()
+ proxy = ThreadLocalStreamProxy(original, "<stdout>")
+
+ results: dict[str, str] = {}
+ barrier = threading.Barrier(2)
+
+ def session(name: str) -> None:
+ buf = io.StringIO()
+ proxy._set_stream(buf)
+ barrier.wait()
+ for _ in range(100):
+ proxy.write(name)
+ proxy.flush()
+ results[name] = buf.getvalue()
+ proxy._clear_stream()
+
+ t1 = threading.Thread(target=session, args=("A",))
+ t2 = threading.Thread(target=session, args=("B",))
+ t1.start()
+ t2.start()
+ t1.join(timeout=5)
+ t2.join(timeout=5)
+
+ assert not t1.is_alive(), "Thread A deadlocked"
+ assert not t2.is_alive(), "Thread B deadlocked"
+ assert results["A"] == "A" * 100
+ assert results["B"] == "B" * 100
+ assert original.getvalue() == ""