Skip to content

Serialize canvas message handling, drawing and timers across threads - #626

Open
f0k wants to merge 1 commit into
matplotlib:mainfrom
f0k:serialize-canvas-access
Open

f0k wants to merge 1 commit into
matplotlib:mainfrom
f0k:serialize-canvas-access

Conversation

@f0k

@f0k f0k commented Nov 28, 2026

Copy link
Copy Markdown

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_lock to 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's Canvas._handle_message() and the draws it triggers therefore run concurrently for the same figure. Matplotlib is not thread-safe.

#610 is one symptom (ParseException in 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. Each draw request 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), draw messages of one figure alternated strictly between MainThread and 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

On current main (with #621) I can still reproduce both parallel Figure.draw calls and the redraw loop.

Change

This PR extends the lock from #603 instead of adding a second one:

  • _lock becomes a threading.RLock.
  • In addition to the global state, it is now also held while:
    • handling canvas messages in Canvas._handle_message(), including the event callbacks run by manager.handle_json() and the toolbar's messages (routed to the same method);
    • drawing in Canvas.draw(), which also covers explicit fig.canvas.draw() calls from user code;
    • rendering with savefig() in Canvas._repr_mimebundle_() (display), Toolbar.export() and Canvas._send_save_buffer() (download button and download());
    • running timer callbacks: new_timer() returns a TimerTornado subclass 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 and mpl_connect callbacks) in Lab, open the RISE preview, run the last cell, then observe the kernel. Matplotlib's Figure.draw was instrumented to count draws running at the same time.

runs max. parallel Figure.draw redraw loop
main (incl. #621) 2 2 (both runs) 1 of 2 (145 draws in 8 s, kernel still busy)
this branch 4 1 0 of 4 (18–20 draws, kernel idle)

As the loop is intermittent, the main evidence is that draws no longer overlap.

Additionally, a script without a kernel exercised the lock directly:

  • Re-entry: a button_press_event callback that creates a figure and calls plt.show(), triggered via Canvas._handle_message(), completes without deadlock.
  • Concurrency: four threads ran at the same time, with a 10 µs thread switch interval: two handling draw messages, 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

  • Remaining limitation: cell code that modifies a figure (e.g. ax.plot(...) or set_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.
  • Code that blocks under the lock: if an event callback waits for something that is handled in another subshell thread (e.g. a reply from the frontend), that thread would block on the lock. ipympl itself never waits like this; it would only affect unusual user callbacks, and any per-canvas lock has the same issue.
  • Workaround for users until this is released: set "Kernel Comms over subshells" to "Disabled" in JupyterLab's settings.

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>
@github-actions

Copy link
Copy Markdown
Contributor

Binder 👈 Launch a binder notebook on branch f0k/ipympl/serialize-canvas-access

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Interactive graph in jupyterlab-rise presentation

1 participant