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
I'll start by exploring the repository structure to understand the codebase.
Assistant
I'll start by exploring the repository structure.
Assistant
This is the Marimo repository. Let me explore the structure more to understand the codebase, especially around print routing and threads.
Assistant
Now let me look at how print is routed/patched. Let me search for where the print builtin might be overridden.
Assistant
The key file is
marimo/_messaging/print_override.py. Let me look at it.Assistant
Now let me find where
print_overrideis installed as the builtinprint.Assistant
Let me look at the streams and how stdout is set up.
Assistant
Let me look at the thread_local_streams.py file.
Assistant
Let me look at the context types and how stdout/stderr are managed.
Assistant
Now let me understand the issue better by reproducing it. Let me first check if Numba is installed.
Assistant
Let me create a reproduction script that simulates what Numba does — checking that
printretains builtin identity.Assistant
I've reproduced the issue. Now let me understand how stdout is set up for the kernel context.
Assistant
Let me look at how the kernel sets up stdout/stderr and where
print_overrideis used in runtime.py.Assistant
Let me check where
sys.stdoutis set for the kernel context.Assistant
Let me look at where
redirect_streamsis called during cell execution.Assistant
Now I understand the issue well. Let me look at the existing tests for print_override and threads to understand the expected behavior.
Assistant
Now let me look at the threads tests to understand how threads route output.
Assistant
Let me look at where
print_overrideis used in runtime.py and the kernel lifecycle.Assistant
Let me look at where
install_thread_local_proxiesis called and how run mode sets up streams.Assistant
Let me look at how
install_thread_local_proxiesis called in the kernel manager and how the streams are set up for run mode vs edit mode.Assistant
Let me look at the
broadcast_notificationfunction and the notification utilities.Assistant
Let me look at the
Stdout/Stderrbase classes and the types.Assistant
Let me look at how streams are created and the
should_redirect_stdio/use_fd_redirectlogic.Assistant
Let me look at how
should_redirect_stdioanduse_fd_redirectare determined, and wherelaunch_kernelis called.Assistant
Let me look at the console output worker to understand buffering.
Assistant
Let me look at the MockStream to understand how operations are captured.
Assistant
Let me look at the kernel test fixture to understand the stream setup.
Assistant
Let me look at the test helper streams.
Assistant
Let me test how CPython's
printcallswriteto understand the buffering implications.Assistant
Now I have a comprehensive understanding. Let me check the imports in runtime.py and look at the capture.py to understand ThreadLocalStreamProxy usage.
Assistant
Let me look at how
capture.pyusesThreadLocalStreamProxyand understand the capture mechanism, since it might be affected by my changes.Assistant
Let me look at the runtime.py around line 2310 where
clear_thread_local_streamsis used.Assistant
Let me look at how
app_host/main.pyinstalls the proxy for run mode.Assistant
Let me look at the
CellOutputclass to understandstdout/stderrmethods.Assistant
Now I have a thorough understanding of the codebase. Let me implement the fix. The core issue is that
print_overrideis installed in the module globals, breaking Numba's identity check forprint. The fix is to:- Not install
print_overridein module globals (keep builtinprint) - Route
mo.Threadoutput through a thread-awaresys.stdout(extending the existingThreadLocalStreamProxymechanism to edit mode) - Create thread stdout/stderr classes that broadcast to the spawning cell
Let me start by refactoring
print_override.pyto add thread stdout/stderr classes:- Not install
Assistant
Now let me refactor
print_override.pyto add thread stdout/stderr classes that broadcast to the spawning cell:Assistant
Now let me update
threads.pyto set up thread-local streams inThread.run():Assistant
Now let me update
Thread.run()to set up thread-local streams. Let me edit therunmethod:Assistant
Let me fix the extra blank line:
Assistant
Now let me update
redirect_streams.pyto unify the proxy branch with OS stream redirection and stdin handling:Assistant
Now let me update the proxy branch to also handle OS stream redirection and stdin. The key insight: when the proxy is installed (now both edit and run mode), I should use
set_thread_local_streamsfor stdout/stderr, AND do OS stream redirection (redirect(stdout)) and stdin swap.The
redirect(stdout)is a no-op for run mode (forward_os_streams=False, _NOOP_WATCHER). For edit mode, it starts the watcher (fd redirection).For stdin: run mode has
stdin=None, edit mode hasstdin=ThreadSafeStdin. I'll swap stdin when it's not None.Let me edit the proxy branch.
Assistant
Now let me update
launch_kernelinruntime.pyto install theThreadLocalStreamProxyand passprint_override_fn=None:Assistant
Now let me check if the
print_overrideimport inruntime.pyis still used:Assistant
The
print_overrideimport is now unused. Let me remove it:Assistant
Let me check the
pyodide_session.pyreference toprint_override_fn:Assistant
Good,
pyodide_session.pyalready passes None. Let me verify the other callers:Assistant
All other callers already pass None. Now let me verify my reproduction script works:
Assistant
Let me fix the SyntaxWarning in the docstring (invalid escape sequence):
Assistant
Now let me update my reproduction script to pass
print_override=None(simulating the production behavior):Assistant
The Numba identity check now passes. Let me run the existing tests to check for breakages:
Assistant
The print_override tests pass. The thread tests need an async plugin. Let me install pytest-asyncio:
Assistant
All thread and print_override tests pass. Let me run a broader set of tests to check for breakages:
Assistant
Only 2 tests failed. Let me check if these are related to my changes. Let me look at the launch kernel event loop test since I modified
launch_kernel:Assistant
Let me look at the test failure details:
Assistant
The failure is in
_bootstrap_subprocess(os.setsid()), which I didn't modify. Let me verify this is pre-existing by stashing my changes:Assistant
Both failures are pre-existing (environment issues, not related to my changes). Now let me write a comprehensive test to verify the new thread routing behavior works end-to-end with the proxy installed:
Assistant
The
test_proxy_routes_to_thread_localpassed but its PASS message went to the stream (because the proxy was routing to it). Let me verify that test more carefully:Assistant
Let me check if
ctx.stdout/ctx.stderrare used anywhere that might affect threads:Assistant
Let me run the capture and redirect-related tests to make sure those still work:
Assistant
Let me look at the redirect_streams tests to understand what they cover:
Assistant
Let me write an integration test that sets up a kernel with the proxy installed (simulating production) and verifies thread routing with builtin print:
Assistant
The builtin print check passes. Let me find the correct
ExecReqProvider:Assistant
The kernel has a multiple definition error from duplicate
moimports. Let me fix the test:Assistant
The integration test passes. Let me check if
print_overrideis referenced anywhere else that I might have missed:Assistant
Let me check where
is_marimo_threadandTHREADSare used:Assistant
Let me review the full diff of all my changes:
Assistant
The diff looks clean. Let me run a broader set of tests to make sure nothing else is broken, including capture, output, and stream-related tests:
Assistant
Let me check the run-mode / app tests to ensure those paths still work:
Assistant
Let me check the default value of
redirect_console_to_browserto understand the impact of the run-mode behavior change:Assistant
So
redirect_console_to_browseris True by default formarimo run(line 611, 826) and False for export (line 1420, 592). For export, console output is not redirected to the browser (it's for exporting to HTML/ipynb).So in run mode,
redirect_console_to_browseris typically True. So the proxy is installed. ✓For export (run mode with redirect_console_to_browser=False), the proxy is NOT installed. Threads' print goes to real stdout. But export doesn't really use threads. So it's fine.
OK so the behavior change only affects run mode with redirect_console_to_browser=False (export), which doesn't use threads. So the behavior change is negligible.
Now, let me reconsider the
IPCcase.is_ipc=Truefor IPC mode.use_fd_redirect = is_subprocess = is_edit_mode or is_ipc. So IPC mode uses fd redirection. Andshould_redirect_stdio = is_edit_mode or redirect_console_to_browser.Assistant
Let me check where IPC mode is used and whether redirect_console_to_browser is True for it.
Assistant
IPC mode has
redirect_console_to_browser=Trueby default, so the proxy is installed there too. Let me run the IPC and session tests:Assistant
The failure is about process group killing (unrelated to my changes). Let me verify it's pre-existing:
Assistant
Confirmed pre-existing and unrelated. Now let me consider the case where
stdoutis aMockStdout(aThreadSafeStdoutsubclass) passed toset_thread_local_streams. When the proxy dispatches, it callsThreadSafeStdout.write→_write_with_mimetype(overridden by MockStdout to append to messages). So the buffering queue is bypassed by the mock. That's fine for tests.But wait — there's a subtle issue. In production edit mode,
ThreadSafeStdout._write_with_mimetypeappends to theconsole_msg_queue(buffered). Andbroadcast_notificationfromThreadStdoutALSO writes to the stream (viastream.write). Let me check: would this cause double-routing in edit mode?When
redirect_streamscallsset_thread_local_streams(stdout, stderr)with (the main thread's), the proxy routes main-thread → → console_msg_queue → buffered_writer → . So main-thread print goes through the queue ONCE.Assistant
The
ThreadStdout/Stderrmatch the originalprint_overridebehavior (no per-write truncation, direct broadcast). Let me run the full runtime + messaging test suite one final time to confirm only pre-existing failures remain:Assistant
Only the 2 pre-existing environment-related failures remain. Now let me try installing numba to do a real end-to-end test:
Assistant
Now let me write a real Numba end-to-end test with the kernel:
Assistant
Numba successfully compiles a function that calls
printin the marimo kernel. Now let me verify that the OLD behavior (with print_override) would have failed, to confirm this was a real bug:Assistant
Let me check whether Numba fell back to object mode or raised a warning with the old behavior:
Assistant
This confirms the bug. With the OLD behavior:
nopython_signatures = []— Numba could NOT compile in nopython mode (failed)compiled = None— compilation failed
With my NEW behavior:
compiled = [(int64,)]— Numba successfully compiled in nopython mode
Let me see the actual Numba error message with the old behavior:
Assistant
This is the exact error described in the issue:
Untyped global name 'print': Cannot determine Numba type of <class 'function'>. Now let me verify my fix resolves it directly:Assistant
The fix works. With the new behavior:
result = 42(correct)signatures = [(int64,)](compiled)nopython = [(int64,) -> int64](compiled in nopython mode — the gold standard)
And
print(x)actually printed21(via sys.stdout).Now let me run the existing print_override and threads tests one final time to confirm they all pass:
Assistant
All 42 tests pass, including the critical
test_thread_printwhich verifies thread print routing. Let me clean up the temporary test files:Assistant
Let me verify the final state of the modified files to make sure everything is consistent:
Assistant
All imports work. Let me run a final lint check to make sure the code style is consistent:
Assistant
Ruff passes. Let me also check the docstring escape issue is resolved and verify the final threads.py:
Assistant
No syntax warnings. Let me do a final review of all the changes:
Assistant
The diff is clean and complete. Let me verify nothing imports
print_overridefromruntime.py(which I removed):Assistant
Nothing imports
print_overridefromruntime.py. Let me run the broader test suite once more to confirm stability, focusing on areas that might be affected by the stream/proxy changes:Assistant
All runtime tests pass (excluding the pre-existing environment failure). Let me also run the export tests since they involve run-mode with
redirect_console_to_browser=False:Assistant
Let me check if these 3 watch failures are pre-existing:
Assistant
All 3 failures are pre-existing (unrelated to my changes — they're about
--watchwithout output file).Let me do a final comprehensive verification with a fresh reproduction of the exact issue scenario, then clean up and submit:
Assistant
All requirements are verified end-to-end. Let me clean up the temporary file:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.