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 and find the relevant files for this issue.
Assistant
Let me start by exploring the repository structure.
Assistant
Let me explore the marimo package structure, focusing on print routing and the
mo.Threadrelated code.Assistant
Now let me look at the threads.py file and the capture.py file.
Assistant
Let me search for
print_overrideto understand how the print routing works.Assistant
Let me look at the messaging streams and thread local streams.
Assistant
Let me look at the runtime.py to understand how the main module is set up with the print override.
Assistant
Now let me look at the kernel_lifecycle.py to understand how the kernel session is set up with the print override.
Assistant
Let me look at the streams.py to understand ThreadSafeStdout and how stdout writes work.
Assistant
Let me look at the tests related to print_override and threads.
Assistant
Now let me look at the test_redirect_streams.py and test_thread_local_proxy.py to understand the expected behavior.
Assistant
Let me search for where
install_thread_local_proxiesis called and understand the run mode flow.Assistant
Let me look at
broadcast_notificationand the notification_utils.Assistant
Let me check the git log for recent context on these files.
Assistant
Let me look at the threads tests and how threads are tested in the runtime.
Assistant
Let me look at the conftest to understand the test kernel setup.
Assistant
Now I understand the test setup. The tests use edit mode with mock streams. The
MockStdout/MockStreamare used.Let me look at the MockStdout and MockStream to understand the test flow.
Assistant
Let me look at where
redirect_streamsis called in the runtime.Assistant
Let me search for code that relies on
sys.stdoutbeing a specific type.Assistant
Let me look at the tracebacks.py code that checks sys.stderr type.
Assistant
Let me search for any hints or TODOs about print routing and Numba.
Assistant
Let me see the full
write_tracebackfunction.Assistant
Let me check if
sys.stdoutis set globally anywhere in edit mode, and look at how the kernel bootstraps.Assistant
Let me check how tests interact with
sys.stdoutduring execution, to assess the impact of changes.Assistant
Let me look at test_streams.py to understand the fileno and stdout behavior tests.
Assistant
Let me look at the
Stdout/Stderrbase classes in types.py.Assistant
Let me look at the kernel bootstrap and startup to see if stdout is set globally.
Assistant
Let me look at the
kandmocked_kernelfixtures in conftest.Assistant
Let me look at the CellOutput class to understand
stdout/stderrhelpers.Assistant
Let me first write a reproduction script to confirm the Numba issue. Let me check if numba is available.
Assistant
Let me write a reproduction script that checks
printidentity in a marimo kernel.Assistant
Let me use the repo's venv.
Assistant
I've reproduced the issue.
printisprint_override, not builtin. Now let me run the existing thread tests to confirm current behavior.Assistant
Let me verify how builtin
printcallssys.stdout.write.Assistant
Let me look at how the kernel module and
__main__relate, and howprint_overridecould be lazily installed.Assistant
Let me examine the KernelRuntimeContext to see how to access the kernel module from
mo.Thread.Assistant
KernelRuntimeContexthasglobalsproperty →self._kernel.globals→kernel._module.__dict__(the__main__.__dict__). Andctx.kernel? Let me check if there's akernelproperty.Assistant
Let me look at the Kernel constructor to understand where
print_override_fncould be stored.Assistant
Let me check the pyodide session usage of print_override_fn.
Assistant
Let me look at the
buffered_writerto understand console message coalescing.Assistant
Let me check if PyodideStream is a ThreadSafeStream subclass.
Assistant
Let me look at the ScriptRuntimeContext.
Assistant
I now have a clear understanding. Let me verify my understanding of the current
printresolution and the lazy-swap approach by examiningcreate_main_moduleclosely.Assistant
Let me check the ruff/lint config to understand constraints on unused parameters.
Assistant
So
ARG(flake8-unused-arguments) is enabled. So if I keep theprint_overrideparam increate_main_modulebut don't use it, ruff would flag it. Let me check the per-file-ignores.Assistant
Let me find all callers of
patch_main_moduleandcreate_main_module.Assistant
There are several callers of
create_main_module:script_context.py:57:create_main_module(file=None, input_override=None, print_override=None).script_runner.py:85, 120: let me check.kernel_runner.py:129:create_main_module(...).kernel_lifecycle.py:153:patch_main_module(file=..., input_override=..., print_override=..., doc=...).
Let me check the script_runner.py and kernel_runner.py callers to see how they pass print_override.
Assistant
Let me look at
initialize_kernel_contextto see how the context gets the kernel.Assistant
I now have a clear plan. The approach: don't install
print_overrideasprintat kernel creation (soprintis the builtin by default, fixing Numba), and lazily installprint_overrideinto the kernel's__main__.__dict__when amo.Threadis created (preserving thread routing). Let me implement this.First, let me update
create_main_moduleandpatch_main_moduleto remove theprintoverride installation:Assistant
Let me check how that test uses the
patch_main_modulemock to ensure removing the param won't break it.Assistant
Let me check how
patch_main_moduleis mocked and whether it asserts on args.Assistant
The test mocks
patch_main_moduleas a whole, so removing the param won't break it. Let me check ifKernelArgs.print_override_fnis read anywhere besidescreate_kernel.Assistant
Let me check all
Kernel(constructor call sites.Assistant
Let me look at the kernel_runner.py Kernel construction.
Assistant
I'll implement the cleaner approach: store
print_override_fnon the kernel and lazily install it when amo.Threadis created. Let me start withpatches.py:Assistant
Now let me update the callers of
create_main_module/patch_main_moduleto drop theprint_overrideargument:Assistant
Now let me update
script_runner.py:Assistant
Now let me update
kernel_runner.py:Assistant
Now let me update
kernel_lifecycle.pyto passprint_override_fnto the Kernel constructor instead ofpatch_main_module:Assistant
Now let me add the
print_override_fnparameter to theKernel.__init__and store it:Assistant
Let me verify
AnyandCallableare imported in runtime.py:Assistant
Anyis imported (line 21).Callableis imported underTYPE_CHECKING(line 166). Butprint_override_fn: Callable[[Any], None] | Noneis a runtime annotation. Since the file usesfrom __future__ import annotations, annotations are strings (not evaluated at runtime). SoCallabledoesn't need to be imported at runtime. But it's imported under TYPE_CHECKING for type checkers. Let me verifyfrom __future__ import annotationsis at the top.Assistant
Good,
from __future__ import annotationsis present, so annotations are strings. Now let me add theprint_overrideproperty toKernelRuntimeContext:Assistant
from __future__ import annotationsis present, soCallablein the annotation is a string. But for type checkers (mypy),Callableneeds to be imported. Let me check the TYPE_CHECKING block in kernel_context.py.Assistant
Now let me update
mo.Thread.__init__to lazily install theprintoverride. Let me view the relevant section:Assistant
Now let me update the repro to check the correct condition and run it:
Assistant
The repro passes. Now let me verify that
mo.Threadprint routing still works. Let me run the thread tests:Assistant
All thread tests pass. Now let me write a comprehensive test script to verify the mo.Thread routing and isolation behavior with the lazy install:
Assistant
Let me simplify the test script using the existing
ExecReqProvider:Assistant
The routing didn't work in my script. Let me debug by printing intermediate values:
Assistant
The lazy install worked (
printisprint_override), but the thread's print didn't produce an op. Let me debug what happens inside the thread:Assistant
Let me check that
get_contextis the same function in bothprint_overrideand the cell'smo._runtime.context:Assistant
Let me add explicit debugging to capture any exception in
print_override:Assistant
My debug script had a bug (
dbg2wasn't declared global). Let me fix it:Assistant
Let me re-examine the
MockStreamclass carefully — I may have misread how it handles an existing stream:Assistant
Let me test
MockStreamwrapping behavior directly to understand:Assistant
Let me run
test_thread_printspecifically with verbose output to check:Assistant
Let me replicate the repo test exactly to understand the
MockStreamwrapping:Assistant
Let me check the imports in the repo
test_threads.py:Assistant
I was using the wrong
MockStream(the repo test usestests._messaging.mocks.MockStreamwhich shares themessageslist). My routing actually works. Let me verify with the correct MockStream:Assistant
Now let me test concurrent thread isolation — that two concurrent
mo.Threads route their prints to their respective spawning cells without mixing:Assistant
Now let me simulate the Numba check more faithfully — a function defined in the kernel that calls
print, and verifyprintresolves to the builtin from the function's__globals__:Assistant
Now let me run the relevant test suites to make sure nothing is broken:
Assistant
All pass. Let me run the runtime tests that involve
patch_main_moduleand the broader runtime/capture tests:Assistant
The only failure is
test_non_windows_does_not_change_event_loop_policywithPermissionError: os.setsid()— this looks environment-related, not from my change. Let me verify by stashing my changes:Assistant
Confirmed — that test fails on the original code too (pre-existing
os.setsid()environment issue), unrelated to my change. Let me run more related tests:Assistant
Let me run the app/script runner tests since I modified those files:
Assistant
Let me find and run script runner tests and the context tests:
Assistant
Let me run the app/script execution tests (those that exercise
create_main_modulein script/app mode):Assistant
Let me run the broader runtime test suite (deselecting the known environment-failing test):
Assistant
All runtime tests pass. Let me verify run-mode behavior with
mo.Thread:Assistant
Let me test the after-cell-execution case (mo.Thread running after the spawning cell finishes) — this is the key case the lazy install preserves:
Assistant
Excellent! The after-cell case works. Let me run the linter on the changed files to ensure no lint errors:
Assistant
The 8 errors are
property-docstring-starts-with-verbon pre-existing properties (cli_args, argv, query_params). Let me confirm they're pre-existing (not from my changes):Assistant
The 8 errors are pre-existing (identical on the original code), so my changes introduce no new lint errors. Let me verify formatting is clean on my changed files:
Assistant
My
sededit left thecreate_main_modulecall on multiple lines; ruff wants it on one line. Let me fix:Assistant
Now formatting is clean. Let me view the final diff to review all my changes:
Assistant
The diff looks clean. Let me run mypy on the changed modules to ensure type correctness:
Assistant
No pip/mypy available. Let me check if there's a way to run mypy. Let me check uv.
Actually, let me check if mypy is available via uv or another path.
Assistant
mypy ran clean. Let me run it on all the changed files with the project config:
Assistant
mypy passes on all changed files. Let me check if any existing tests assert on the old
printoverride behavior (which my change would break):Assistant
Let me check no test directly calls
create_main_module/patch_main_modulewith theprint_overrideargument:Assistant
Let me run the session manager and asgi tests that mention
patch_main_module:Assistant
Let me check if these asgi failures are pre-existing by stashing my changes:
Assistant
The asgi failures are pre-existing (same 15 fail on the original code). My changes don't introduce new failures. Let me clean up temp files and run the key tests one final time:
Assistant
Let me run the full
_messagingtest directory to be thorough:Assistant
All messaging tests pass. Let me do a final review of the complete diff:
Assistant
Everything is wired correctly. Let me do a final end-to-end verification recreating the repro:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.