Repository navigation
Conversation
With ipykernel >= 7, comm messages can be handled in several threads (kernel subshells). When a figure is displayed in more than one frontend (e.g., JupyterLab with "comms over subshells" plus a RISE preview), the messages of the different frontends end up in different threads, and the same figure is drawn concurrently. Matplotlib is not thread-safe; besides parser errors (see matplotlib#610), this can start an endless redraw loop between the frontends that keeps the kernel busy. Make the module lock from matplotlib#603 reentrant and also hold it while handling canvas messages (including event callbacks), drawing, rendering figures with savefig() (display, export, download) and running timer callbacks. Using a single lock avoids deadlocks from inconsistent lock ordering, e.g., when an event callback creates or shows a figure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human summary
As described in #612, one of my lecture slide decks using RISE and interactive plots with callbacks stopped getting interactive plots with ipympl 0.9.8. In 0.9.0, interactive plots are created, but go into an endless redrawing loop when RISE and the notebook are open at the same time. jupyterlab-contrib/rise#147 fixes RISE to give interactive plots even with the latest ipympl, but the endless redrawing persists.
With the help of Claude Code, the redrawing loop could be traced back to multiple threads trying to render the same figure. This is related to the commsOverSubshells setting enabled by default (jupyterlab/jupyterlab#19719). The idea is that interactive plots should remain responsive while the main thread is executing another notebook cell, but it breaks down when there are multiple views of the same figure open at the same time.
Claude suggested to add a re-entrant
canvas_lockto guard the canvas, but noticed that it could create a deadlock with the lock introduced in #603. I suggested to reuse the lock of #603 instead, which would avoid the deadlock. With this fix, the notebook and RISE preview can render simultaneously again, even when the commsOverSubshells setting is enabled.Fixes #612.
The remaining explanation below is provided by Claude.
Problem
With ipykernel >= 7 and JupyterLab >= 4.4 ("Kernel Comms over subshells" defaults to
perCommTarget), comm messages of a figure are handled in different threads: the main thread (e.g. during cell execution) and one subshell thread per frontend. ipympl'sCanvas._handle_message()and the draws it triggers therefore run concurrently for the same figure. Matplotlib is not thread-safe.#610 is one symptom (
ParseExceptionin mathtext), addressed by #621 by locking the mathtext parser. A second symptom: when a figure is displayed in two frontends whose messages arrive in different threads, the frontends can get into an endless redraw loop. Eachdrawrequest from one frontend leads to a draw that makes both frontends request another draw. The kernel stays busy, with continuous network and CPU load.Observed setup: JupyterLab 4.6.6 plus a RISE preview of the same notebook. The preview bundles an older JupyterLab, so its comm messages arrive on the main thread, while Lab's go to a subshell. In the kernel (ipympl 0.9.8),
drawmessages of one figure alternated strictly betweenMainThreadand the subshell thread (321 + 321 within 15 s), with two draws of the same figure running at the same time. The loop is intermittent; once it starts, it continues indefinitely.Relation to #603 and #621
_lockto protect global state:Gcf,display(), figure creation,show()andflush_figures(). It doesn't cover per-canvas message handling or drawing, so the same figure can still be drawn from several threads at once.main, after 0.10.0) serializes the mathtext parser only. That fixes theParseExceptionfrom Error withipykernel>=7in combination withplt.tight_layout#610, but neither concurrent drawing as a whole nor concurrently running event callbacks (mpl_connecthandlers, which modify artists).On current
main(with #621) I can still reproduce both parallelFigure.drawcalls and the redraw loop.Change
This PR extends the lock from #603 instead of adding a second one:
_lockbecomes athreading.RLock.Canvas._handle_message(), including the event callbacks run bymanager.handle_json()and the toolbar's messages (routed to the same method);Canvas.draw(), which also covers explicitfig.canvas.draw()calls from user code;savefig()inCanvas._repr_mimebundle_()(display),Toolbar.export()andCanvas._send_save_buffer()(download button anddownload());new_timer()returns aTimerTornadosubclass whose_on_timer()holds the lock.Why one lock: with separate locks for global state and canvases, both orders occur.
show()/flush_figures()hold the global lock and render the canvas. An event callback holds the canvas lock and may create or show a figure. Since callbacks are user code, a consistent lock order can't be enforced, so two locks risk deadlocks. A single reentrant lock avoids this: nesting in one thread re-enters, other threads wait.Reentrant because handling a message may draw, and callbacks may create or show figures. As a side effect, this also makes #603's code paths safe against re-entry, which would block forever with the previous non-reentrant
Lock.Cost: all figure operations in the kernel are serialized. As drawing is GIL-bound anyway, this costs no throughput, only waiting time when several threads draw at once.
Testing
The kernel used this branch's Python code with the 0.10.0 frontend (JS 0.12.0), on ipykernel 7.4.0, JupyterLab 4.6.6, matplotlib 3.10.9. The scenario: run a notebook with three ipympl figures (one with
$a$/$b$axis labels andmpl_connectcallbacks) in Lab, open the RISE preview, run the last cell, then observe the kernel. Matplotlib'sFigure.drawwas instrumented to count draws running at the same time.Figure.drawmain(incl. #621)As the loop is intermittent, the main evidence is that draws no longer overlap.
Additionally, a script without a kernel exercised the lock directly:
button_press_eventcallback that creates a figure and callsplt.show(), triggered viaCanvas._handle_message(), completes without deadlock.drawmessages, one rendering via_repr_mimebundle_()with changing mathtext titles, and one firing timer callbacks that draw. All completed without errors or deadlock.The test suite passes (39 passed).
Notes for reviewers
ax.plot(...)orset_xlabel(...)in a cell) runs in the main thread outside ipympl and can't be serialized by it. A draw triggered by a frontend in a subshell can still overlap with such code. Avoiding this entirely needs comms to be handled on the main thread.