ISSUE DESCRIPTION Marimo's print routing breaks Numba compilation In notebooks that do…
- User
ISSUE DESCRIPTION
Marimo's print routing breaks Numba compilation
In notebooks that do not use
mo.Thread,printmust retain builtin identity so Numba can compile functions that call it.mo.Threadmust continue routing output to the spawning cell, with output isolation between concurrent threads.Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /marimo, current file: none) bash-$
Assistant
Let me start by understanding the repository structure and the issue at hand. The issue is about Marimo's print routing breaking Numba compilation. The key points are:
- In notebooks that don't use
mo.Thread,printmust retain builtin identity so Numba can compile functions that call it. mo.Threadmust continue routing output to the spawning cell, with output isolation between concurrent threads.
Let me first explore the repository structure to understand how it's organized.
- In notebooks that don't use
Assistant
Let me explore the marimo source directory and look for print routing and Thread-related code.
Assistant
Let me search for print routing related code.
Assistant
Let me look at the patches.py file, capture.py, and threads.py since they seem most relevant:
Assistant
Now let me look at the capture.py file:
Assistant
Now let me look at the threads.py file:
Assistant
Now let me look at the ThreadLocalStreamProxy and related stream files:
Assistant
Now let me search for where
printis being overridden and how it relates to Numba:Assistant
Now I understand the issue. The
print_overridefunction inprint_override.pyis used as theprintoverride in the main module. The problem is that Numba checks ifprintis the builtinprintfor compilation purposes. When marimo replacesprintwithprint_override, even though it's decorated with@functools.wraps(print), Numba can't recognize it as the builtin print.The issue states:
- In notebooks that do NOT use
mo.Thread,printmust retain builtin identity so Numba can compile mo.Threadmust continue routing output to the spawning cell
The key insight is that the
print_overridefunction is always set as theprintin the module, but it only does special routing when the current thread is inTHREADS. For non-thread cases, it just calls_original_print.The solution should be to NOT override
printin the module's globals at all when not needed for thread routing. Let me look at where the print override is installed:- In notebooks that do NOT use
Assistant
Now let me look at how the
print_override_fnis passed:Assistant
Let me see more context around where
print_overrideis used inruntime.py:Assistant
Now let me look at how tests might be structured for this. Let me search for any existing tests related to print override or Numba:
Assistant
Now let me understand the issue better. The problem is that
printis being overridden in the module's__dict__withprint_override, which breaks Numba's ability to recognize the builtinprint. Numba checks for builtin identity.The key is: when
mo.Threadis NOT being used (i.e., no threads inTHREADS),printshould be the actual builtinprint. But whenmo.ThreadIS being used, we need the routing functionality.Looking at the code flow:
print_overrideis always passed topatch_main_modulein kernel mode- In
create_main_module,print_overrideis set via_module.__dict__.setdefault("print", print_override) - This means
printin the module is alwaysprint_override, not the builtinprint
The solution should be to NOT override
printat the module level. Instead, we should use thesys.stdoutredirection approach that's already being used (viaThreadLocalStreamProxyor stream handling). This way,printremains the builtin, but output is still routed correctly.Let me check how stdout is set up in the kernel context:
Assistant
Let me also check what happens with stdout in the streams:
Assistant
Let me look at the stream implementations to understand how stdout/stderr are handled:
Assistant
Now I understand the architecture better. The key insight is:
sys.stdoutandsys.stderrare already being set to custom stream classes (ThreadSafeStdout/ThreadSafeStderr) that route output properly- Additionally,
printis being overridden in the module's__dict__withprint_override - The
print_overridefunction is mainly needed formo.Threadcases where stdout/stderr are set toNone
Let me verify this by looking at how
mo.Threadsets up its context:Assistant
So in
mo.Thread, the context'sstdoutandstderrare set toNone. This means that for threads, the print override is the mechanism that routes output. But for non-thread cases,sys.stdoutis already aThreadSafeStdoutwhich routes output correctly.The problem is that
print_overrideis always set in the module's globals, even when threads aren't used. This breaks Numba's check for builtinprint.The solution should be: don't set
print_overridein the module's__dict__for the main kernel module. Thesys.stdout/sys.stderrredirection is already sufficient for non-thread output routing. Formo.Thread, theprint_overridefunction is still needed since threads set stdout/stderr to None - but this only needs to work inside the thread, not at the module level.Wait, let me reconsider. When a
mo.Threadruns, it has its own context with stdout/stderr = None. The thread'srun()method callsinitialize_context(self._marimo_ctx). Theprint_overridefunction checks if the current thread ID is inTHREADS, and if so, it routes the output via the context's stream.So the issue is:
printis overridden at the module level withprint_override- Numba checks if
print is builtin.print- this fails becauseprintisprint_override - But
print_overrideforwards to_original_printwhen not in a thread
The solution is to NOT override
printat the module level at all. Sincesys.stdoutis alreadyThreadSafeStdoutfor non-thread cases, output goes through the right channels. For thread cases, we need another approach.Looking more carefully at the thread case: when a thread runs,
sys.stdoutis still the process-levelsys.stdout(aThreadSafeStdoutor aThreadLocalStreamProxy), but the thread's context hasstdout = None. So we need a way for threads to use their own print routing.Let me check how threads handle
sys.stdout:Assistant
Let me look at the redirect_streams.py:
Assistant
Now I have a much clearer picture. Let me understand the flow:
-
In edit mode:
sys.stdout/sys.stderrare replaced withThreadSafeStdout/ThreadSafeStderrduring cell execution. This meansprint()(the builtin) writes to these custom streams and output is routed correctly. -
In run mode:
ThreadLocalStreamProxyis installed forsys.stdout/sys.stderr. During cell execution,set_thread_local_streams()registers the per-thread streams. -
For mo.Thread: The thread's context has
stdout = Noneandstderr = None, soredirect_streamsis a no-op. Theprint_overridefunction is needed to route output.
The key issue is that
print_overrideis set in the module's__dict__, which breaks Numba's identity check forprint. But for non-thread cases,sys.stdoutredirection is already sufficient.The fix should be:
- Don't pass
print_overridetopatch_main_module- remove the print override from the module's__dict__ - Keep
print_overridefunctional formo.Thread- but sinceprintisn't in the module globals anymore, threads won't automatically use it
Wait, let me think more carefully. When a
mo.Threadruns, what doesprint()resolve to?In Python,
print()inside a thread's function would resolve from:- Local scope
- Enclosing scopes
- Global scope (the module's
__dict__) - Builtins
If we remove
printfrom the module's__dict__, thenprint()in a thread would resolve tobuiltins.print, which writes tosys.stdout. But in a thread,sys.stdoutis the same as the main process'ssys.stdout(eitherThreadSafeStdoutorThreadLocalStreamProxy). This might route the output to the wrong cell.Let me check what happens with
sys.stdoutinside a thread more carefully:-
Assistant
Let me look at how the mo.Thread's stream is set up:
Assistant
Now I see the issue more clearly:
-
For
mo.Thread, a new stream is created withredirect_console=Falseand the samecell_idas the parent. The thread'sstdoutandstderrare set toNone. -
Since
stdout/stderrareNone,redirect_streams()becomes a no-op, sosys.stdout/sys.stderrare NOT changed inside the thread. -
The
print_overridefunction is the only mechanism that routes output from threads correctly - it checks the thread's context and sends output viabroadcast_notificationto the stream.
The key insight is:
print_overrideneeds to work inside the thread, but it doesn't need to be in the module's__dict__for the main thread. Instead, we should:- Not set
print_overridein the main module's globals - this preserves builtinprintidentity for Numba - Set
printtoprint_overrideonly insidemo.Thread.run()- this ensures thread output is routed correctly
Let me check the
Thread.run()method more closely:-
Assistant
Now I have a clear plan. The solution is:
-
Don't pass
print_overridetopatch_main_module(or passNone) - this keepsprintas the builtin in the module's globals, satisfying Numba's identity check. -
Modify
mo.Thread.run()to injectprint_overrideinto the module's globals at thread start time and restore it at thread end. This ensuresprintinside a thread uses the overridden version.
Let me first create a test script to reproduce the issue:
-
Assistant
The module isn't installed in the system path, let me use the virtual environment.
Assistant
This confirms the issue. When
print_overrideis passed tocreate_main_module, theprintin the module's__dict__is no longer the builtinprint, which breaks Numba's identity check.Now let me verify the fix approach. The plan is:
- Don't override
printat module creation time (passNoneforprint_override) - Have
mo.Threadset upprint_overridein its module's globals when the thread starts
Let me check the relevant files and make the changes:
- Don't override
Assistant
Now let's implement the fix. First, let's modify the
print_override.py- we need to ensure the function is still available, but we won't install it at module level:Assistant
Now let me modify the
threads.pyto set up and tear downprintoverride in the module globals:Assistant
Now let me implement the changes. The key changes are:
- In
threads.py: Overrideprintin the module's__dict__when amo.Threadstarts, and restore it when the thread ends. - In
runtime.py: Don't passprint_overrideto the kernel's main module (passNoneinstead).
Let me start with the
threads.pychange:- In
Assistant
I need to fix the edit command syntax. The
--fileoption should be used correctly. Let me use the correct syntax.Assistant
It seems like the file got partially replaced incorrectly. Let me restore it and try again:
Assistant
Good, the file is restored. Let me now make the changes properly using the heredoc syntax:
Assistant
The imports are updated. Now I need to modify the
runmethod to injectprint_overrideinto the module's globals. Let me see the current run method:Assistant
Now I'll update the
runmethod to overrideprintin the module's__dict__:Assistant
The
threads.pyfile is updated. Now I need to modify theruntime.pyto NOT passprint_overrideto the kernel's main module:Assistant
Now let me also check if the import is still needed in runtime.py:
Assistant
The import is still there but no longer used. Let me remove it:
Assistant
Now let me also check that the import for
print_overrideisn't used anywhere else in runtime.py:Assistant
Good, the import is removed and the only reference is the
Nonevalue. Now let's run the tests to verify the changes work:Assistant
There's a circular import issue.
threads.pyimportsprint_override, andprint_override.pyimportsTHREADSfromthreads.py. I need to handle this differently.Let me move the import to inside the
runmethod to avoid the circular import:Assistant
Let me now make the changes more carefully, avoiding the circular import:
Assistant
Now let me write the updated file with the import inside the method:
Assistant
Now let me also revert the changes to runtime.py (since we need to re-apply them properly):
Assistant
Now apply the change to remove the print_override from the kernel:
Assistant
Also remove the unused import:
Assistant
Now let's run the tests:
Assistant
All tests pass. Now let me create a test script to verify that the fix works for the Numba case:
Assistant
The fix works. Now let me clean up and run some more tests to make sure I haven't broken anything:
Assistant
Let me run the thread-related tests:
Assistant
All thread-related tests pass, including the
test_thread_printtest. Let me also run some broader tests to make sure I haven't broken anything else:Assistant
The only failure is unrelated to our change (it's a
PermissionErrorfromos.setsid()which is a container permission issue, not related to our changes). Let me verify by checking if this test was already failing before my changes:Assistant
The test was already failing before my changes. Let me restore my changes:
Assistant
The changes have been restored. Let me continue with testing to make sure everything works correctly.
Assistant
All thread tests pass, including
test_thread_print. Let me also run a broader set of tests to make sure nothing else is broken, particularly around the patches module and the kernel lifecycle.Assistant
The user is reminding me that I need to use a tool call. Let me continue running tests to verify my changes.
Assistant
Let me check if there are any other places where
print_overrideis used that might need updating:Assistant
Let me verify the test that checks thread print behavior is working correctly:
Assistant
The user hasn't said anything new. The shell prompt is just showing. I should continue verifying my changes and make sure everything is working. Let me review what I've done and consider edge cases.
Let me think about edge cases:
-
Multiple concurrent mo.Threads: Each thread sets
printin__main__.__dict__when it starts and restores it when it ends. If two threads run concurrently, there could be a race condition where one thread's restoration overwrites another thread's override. However, since both are setting it toprint_override, this should be fine. -
Nested mo.Threads: If a mo.Thread spawns another mo.Thread, the inner thread will also set up
print_override. When the inner thread finishes, it will restore the previous value, which should beprint_overridefrom the outer thread. This should work correctly. -
Thread exception: If an exception occurs in the thread's
run()method, thefinallyblock should still execute and clean up properly. I have this covered with the try/finally block. -
Non-kernel context: If
_marimo_ctxisNone(e.g., running in script mode), the thread won't set up the print override. This is probably fine since in script mode, print doesn't need special routing.
Wait, let me check - in the current implementation, the print override is only set up if
self._marimo_ctx is not None. But actually, looking at my code, the print override setup happens regardless of whether_marimo_ctxis None. Let me check my implementation again...Actually, looking at my code:
def run(self) -> None: if self._marimo_ctx is not None: try: initialize_context(self._marimo_ctx) except RuntimeError: pass output = CellOutputList() if self._marimo_ctx is not None: if (exec_ctx := self._marimo_ctx.execution_context) is not None: output = exec_ctx.output if isinstance(self._marimo_ctx, KernelRuntimeContext): self._marimo_ctx.execution_context = ExecutionContext(...) thread_id = threading.get_ident() THREADS.add(thread_id) # Override print in __main__ ... from marimo._messaging.print_override import print_override main_mod = sys.modules.get("__main__") old_print = main_mod.__dict__.get("print") if main_mod is not None else None if main_mod is not None: main_mod.__dict__["print"] = print_override try: super().run() finally: ...The print override is set up regardless of
_marimo_ctx. But wait, if_marimo_ctxisNone, the thread's ID is still added toTHREADS, soprint_overridewould think it's a marimo thread and try to get the context. Let me check what happens whenget_context()fails:In
print_override:try: ctx = get_context() except ContextNotInitializedError: _original_print(*args, **kwargs) returnSo if there's no context, it falls back to the original print. This is correct.
But actually, there's a subtle issue: if
_marimo_ctx is None, the thread is added toTHREADSbut no context is initialized. Soprint_overridewill always fall back to_original_print. This is fine for script mode where print routing isn't needed.However, I should consider whether we even need to override print if
_marimo_ctx is None. Let me think...Actually, the
print_overridefunction checks if the thread ID is inTHREADS. If the thread is inTHREADSbut has no context, it just calls_original_print. So it's a no-op in that case. The only overhead is the function call itself.For the case where
_marimo_ctx is not None, the context is initialized and the print override will work correctly.I think my implementation is correct. Let me also make sure the thread cleanup happens even if
_marimo_ctx is None. Looking at my code:try: super().run() finally: if main_mod is not None: if old_print is not None: main_mod.__dict__["print"] = old_print elif "print" in main_mod.__dict__: del main_mod.__dict__["print"] THREADS.remove(thread_id) teardown_context()Wait,
THREADS.remove(thread_id)andteardown_context()are in thefinallyblock, so they always run. But the original code had them outside any try/except, andTHREADS.add(thread_id)happens before the try block. So if an exception occurs during the setup (beforesuper().run()), the thread ID might be added toTHREADSbut never removed.Actually, looking more carefully at my code, the try/finally wraps
super().run(), andTHREADS.add(thread_id)happens before the try block. So if an exception occurs betweenTHREADS.add(thread_id)andsuper().run(), the finally block would still run and remove the thread ID. But wait,teardown_context()is also in the finally block, which might fail if no context was initialized.Let me check the original code more carefully:
def run(self) -> None: if self._marimo_ctx is not None: try: initialize_context(self._marimo_ctx) except RuntimeError: pass output = CellOutputList() if self._marimo_ctx is not None: if (exec_ctx := self._marimo_ctx.execution_context) is not None: output = exec_ctx.output if isinstance(self._marimo_ctx, KernelRuntimeContext): self._marimo_ctx.execution_context = ExecutionContext(...) thread_id = threading.get_ident() THREADS.add(thread_id) super().run() THREADS.remove(thread_id) teardown_context()In the original code, if
super().run()raises an exception,THREADS.remove(thread_id)andteardown_context()wouldn't run. My fix addresses this by putting them in a finally block.But actually, I should also handle the case where
teardown_context()might fail if no context was initialized. Let me check whatteardown_context()does:Actually, looking at the original code,
teardown_context()is called unconditionally at the end. So it should handle the case where no context was initialized. Let me check if this is the case.Let me also consider: should I only set up the print override if
_marimo_ctx is not None? This would avoid unnecessary overhead for threads that don't need it. But actually, looking at the__init__method,_marimo_ctxis only set ifruntime_context_installed()returns True. So if_marimo_ctx is None, we're not in a marimo kernel context, and print override isn't needed anyway.Actually, let me reconsider. The current code adds the thread ID to
THREADSregardless of whether_marimo_ctxis set. This meansprint_overridewill check for the context and fall back to original print if no context. But if we're not in a kernel context, we probably don't want to add toTHREADSat all.Wait, but the original code also adds to
THREADSregardless. So my change maintains the same behavior.Let me also think about whether there are any issues with the print override being set on
__main__module. In a kernel context,__main__is the module created bypatch_main_module. Each kernel has its own__main__module, so different notebooks running in different kernels would have different modules. But within the same kernel, there's only one__main__module, so concurrent mo.Threads in the same kernel would share the same module.If two concurrent threads both set
printtoprint_override, and one finishes and restores the old value (which would beprint_overridefrom the other thread), the other thread would still work correctly becauseprint_overrideis still in place.Wait, but if the first thread was the only one that set
print_override, and it restoresold_printwhich wasNone(meaningprintwasn't in the dict before), then the second thread's print calls would use the builtin print instead ofprint_override. But actually,old_printwould beNoneonly ifprintwas never in__main__.__dict__. If another thread had already set it toprint_override,old_printwould beprint_override.Let me trace through the scenario:
- Main thread:
printis not in__main__.__dict__(our fix) - Thread A starts:
old_print = main_mod.__dict__.get("print")->None, setsprint = print_override - Thread B starts:
old_print = main_mod.__dict__.get("print")->print_override, setsprint = print_override - Thread A finishes:
old_print is None, so it checks"print" in main_mod.__dict__-> True, so it deletesprint. BUG! This removes the print override that Thread B needs.
This is a problem! I need to fix this. Instead of deleting when
old_print is None, I should only restore if the current value is the one I set.Actually, let me reconsider. The issue is that concurrent threads can interfere with each other's print restoration. A better approach might be to use a reference count or just leave
print_overridein place once it's set.Actually, the simplest fix is to not delete
printifold_print is None. Instead, just leaveprint_overridein place. This way, even if one thread finishes, another thread's print calls still work.But wait, this means
printwould never be restored to the builtin after all threads finish. Is that a problem?Hmm, looking at the original behavior,
printwas alwaysprint_overridein the module, so this isn't a regression. The original code always setprint_overrideat module creation time, and it never went back to the builtin.But the issue is that we want
printto be the builtin for Numba compatibility. If we leaveprint_overridein place after a thread runs, Numba would still fail.Let me think about this differently. The goal is:
- In the main thread (not in mo.Thread),
printshould be the builtin. - In a mo.Thread,
printshould route output correctly.
For the main thread, we're not setting
print_overrideanymore, soprintresolves to builtin. For mo.Threads, we setprint_overridewhen the thread starts and restore when it ends.The concurrent thread issue: if Thread A finishes and removes
print, Thread B's subsequent print calls would use the builtin. But Thread B's ID is still inTHREADS, so if we had keptprint_overrideas a global override, it would still route correctly.The problem is that without
printbeingprint_overridein the module's dict, Thread B's print calls go to the builtin print, which writes tosys.stdout. In edit mode,sys.stdoutis aThreadSafeStdout, which would route to the current cell, not the thread's cell.Wait, but in a mo.Thread,
stdoutis set toNone, andredirect_streamsis a no-op. Sosys.stdoutin the thread is the same as the main thread'ssys.stdout. If that's aThreadSafeStdout, it would route to the main cell, not the thread's cell.So we do need
print_overridefor thread output routing. And we need it to be in the module's dict while any mo.Thread is running.Let me fix the concurrent thread issue with a reference count:
<tool_call> <function=bash_terminal> <parameter=command> cat > /tmp/threads_new.py << 'ENDOFFILE'
Copyright 2026 Marimo. All rights reserved.
from future import annotations
import sys import threading from typing import Any
from marimo._messaging.streams import ThreadSafeStream from marimo._output.rich_help import mddoc from marimo._runtime.cell_lifecycle_item import CellLifecycleItem from marimo._runtime.cell_output_list import CellOutputList from marimo._runtime.context.kernel_context import KernelRuntimeContext from marimo._runtime.context.script_context import ScriptRuntimeContext from marimo._runtime.context.types import ( ExecutionContext, RuntimeContext, get_context, initialize_context, runtime_context_installed, teardown_context, )
Set of thread ids for running mo.Threads
THREADS: set[int] = set()
Reference count for print override in main module globals.
Incremented when a mo.Thread starts, decremented when it ends.
print_override is installed in main when the count goes from 0 to 1,
and removed when it goes back to 0.
_print_override_count = 0 _print_override_lock = threading.Lock()
@mddoc class Thread(threading.Thread): """A Thread subclass that can communicate with the frontend.
`mo.Thread` has the same API as threading.Thread, but `mo.Thread`s are able to communicate with the marimo frontend, whereas `threading.Thread` can't. Threads can append to a cell's output using `mo.output.append`, or to the console output area using `print`. The corresponding outputs will be forwarded to the frontend. Writing directly to sys.stdout or sys.stderr, or to file descriptors 1 and 2, is not yet supported. **Thread lifecycle.** When the cell that spawned this thread is invalidated (re-run, deleted, interrupted, or otherwise errored), this thread's `should_exit` property will evaluate to `True`, at which point it is the developer's responsibility to clean up their thread. Examples: ```python def target(): import time import marimo as mo thread = mo.current_thread() while not thread.should_exit: time.sleep(1) print("hello") ``` ```python import marimo as mo mo.Thread(target=target).start() ``` """ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self._marimo_ctx: RuntimeContext | None = None exit_event = threading.Event() self._exit_event = exit_event if not runtime_context_installed(): return class ThreadLifecycle(CellLifecycleItem): def create(self, context: RuntimeContext) -> None: del context def dispose(self, context: RuntimeContext, deletion: bool) -> bool: del context del deletion exit_event.set() return True ctx = get_context() ctx.cell_lifecycle_registry.add(ThreadLifecycle()) if isinstance(ctx, KernelRuntimeContext): self._marimo_ctx = KernelRuntimeContext(**ctx.__dict__) # standard IO is not yet threadsafe self._marimo_ctx.stdout = None self._marimo_ctx.stderr = None if isinstance(ctx.stream, ThreadSafeStream): self._marimo_ctx.stream = type(ctx.stream)( pipe=ctx.stream.pipe, # TODO(akshayka): stdin is not threadsafe input_queue=ctx.stream.input_queue, cell_id=ctx.stream.cell_id, redirect_console=False, ) else: raise RuntimeError( "Unsupported stream type " + str(type(ctx.stream)) ) elif isinstance(self._marimo_ctx, ScriptRuntimeContext): # Standard streams are not rerouted when running as a script, so no # need to set to None self._marimo_ctx = ScriptRuntimeContext(**ctx.__dict__) if isinstance(ctx.stream, ThreadSafeStream): self._marimo_ctx.stream = ThreadSafeStream( pipe=ctx.stream.pipe, input_queue=ctx.stream.input_queue, cell_id=ctx.stream.cell_id, redirect_console=False, ) else: raise RuntimeError( "Unsupported stream type " + str(type(ctx.stream)) ) @property def should_exit(self) -> bool: """Whether this thread should exit. Returns `True` when the cell that spawned this thread has been invalidated; for example, if the cell: - was re-run - was deleted - was interrupted then this property evaluates to True. It is the developer's responsibility to clean up and finish their thread when this flag is set. Retrieve the current `mo.Thread` with ```python import marimo as mo mo.current_thread() ``` """ return self._exit_event.is_set() def run(self) -> None: global _print_override_count if self._marimo_ctx is not None: try: initialize_context(self._marimo_ctx) except RuntimeError: pass output = CellOutputList() if self._marimo_ctx is not None: if (exec_ctx := self._marimo_ctx.execution_context) is not None: # Share the parent's CellOutputList so appends from threads # are visible to the main execution context. output = exec_ctx.output if isinstance(self._marimo_ctx, KernelRuntimeContext): self._marimo_ctx.execution_context = ExecutionContext( cell_id=self._marimo_ctx.stream.cell_id, # type: ignore setting_element_value=False, output=output, ) thread_id = threading.get_ident() THREADS.add(thread_id) # Override print in __main__ so output from this thread is routed to # the correct cell. Use a reference count so that concurrent threads # don't interfere with each other. # Import here to avoid circular import (print_override imports THREADS # from this module). from marimo._messaging.print_override import print_override install_print_override = False with _print_override_lock: _print_override_count += 1 if _print_override_count == 1: # First thread: install print override main_mod = sys.modules.get("__main__") if main_mod is not None and "print" not in main_mod.__dict__: main_mod.__dict__["print"] = print_override install_print_override = True try: super().run() finally: with _print_override_lock: _print_override_count -= 1 if _print_override_count == 0 and install_print_override: # Last thread finished: remove print override main_mod = sys.modules.get("__main__") if main_mod is not None and "print" in main_mod.__dict__: del main_mod.__dict__["print"] THREADS.remove(thread_id) teardown_context()def current_thread() -> Thread: """Return the
marimo.Threadobject for the caller's thread of control.Returns: The current `marimo.Thread` object. Raises: RuntimeError: If the current thread of control is not a `marimo.Thread`. """ thread = threading.current_thread() if not isinstance(thread, Thread): raise RuntimeError( "mo.current_thread() must be called from a " "thread created with mo.Thread." ) return threaddef is_marimo_thread() -> bool: try: current_thread() return True except RuntimeError: return False ENDOFFILE cp /tmp/threads_new.py /marimo/marimo/_runtime/threads.py </tool_call>
-
Assistant
I need to use a proper tool call format.
Assistant
Now let me run the tests again to make sure the changes work correctly:
Assistant
All tests pass. Let me create a comprehensive test script to verify the fix handles both the Numba case and concurrent threads:
Assistant
All tests pass. Let me clean up the test file and run a broader set of tests to ensure the changes don't break anything else.
Assistant
Let me run a broader set of tests to ensure nothing is broken:
Assistant
The only failure is a pre-existing permission issue unrelated to my changes (confirmed earlier). Let me run more tests excluding that one:
Assistant
All tests pass (except for the pre-existing permission issue unrelated to my changes). Let me verify my final changes by reviewing the diff:
Assistant
Let me review my changes one more time and submit the solution.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →