Skip to content

A subshell request becomes the parent of later output from threads started on the main shell #1603

Backlog

Description

@MichengLiang

Output from a thread started by a main-shell cell is parented to whichever request was handled most recently — including a request handled on a subshell. A thread that prints after a subshell execute_request has been handled shows up under that subshell request instead of the main shell's cell.

"""A subshell request becomes the parent of later output from a main-shell thread."""
import time
from _kernel import Kernel

k = Kernel()
sub = k.subshell()
started = k.run('import threading, time\nthreading.Thread(target=lambda: (time.sleep(0.5), print("from the thread"))).start()')
peek = k.run("1 + 1", subshell=sub)
time.sleep(1)
where = {"cell that started the thread": started, "subshell request": peek}
print({name: k.stdout(msg_id) for name, msg_id in where.items()})
k.close()

Output:

{'cell that started the thread': '', 'subshell request': 'from the thread\n'}

A plain thread starts with an empty context, so Kernel._get_shell_context_var falls back to self._shell_context. set_parent replaces self._shell_context with copy_context() on every call, from whichever thread handles the request, so a subshell request overwrites the fallback that the main shell's threads use. (The "goes to the most recent request" part is the behaviour discussed in #1289; the new part is that subshell traffic — e.g. a variable inspector or any tool using subshells to stay responsive — now redirects main-shell thread output, and frontends drop it because they do not route that parent to the cell. #1564 is the same family: a subshell's handling leaking into what the main shell's output is parented to.)

A possible fix is to update the shared fallback only when set_parent runs on the main shell thread (or keep one fallback per subshell).

_kernel.py: a small jupyter_client helper the scripts share
import queue, threading, time
from collections import defaultdict
from jupyter_client import KernelManager


class Kernel:
    """Start an ipykernel; collect iopub messages and shell replies by parent msg_id in background threads."""

    def __init__(self, *args):
        self.km = KernelManager(kernel_name="python3")
        self.km.start_kernel(extra_arguments=list(args))
        self.kc = self.km.client()
        self.kc.start_channels()
        self.kc.wait_for_ready(timeout=30)
        self.iopub, self.idle, self.stop = defaultdict(list), defaultdict(threading.Event), False
        self.thread = threading.Thread(target=self._pump, daemon=True)
        self.thread.start()

    def _pump(self):
        while not self.stop:
            try:
                msg = self.kc.get_iopub_msg(timeout=0.2)
            except queue.Empty:
                continue
            parent = msg["parent_header"].get("msg_id")
            self.iopub[parent].append(msg)
            if msg["msg_type"] == "status" and msg["content"]["execution_state"] == "idle":
                self.idle[parent].set()

    def subshell(self):
        request = self.kc.session.msg("create_subshell_request", {})
        self.kc.control_channel.send(request)
        return self.kc.get_control_msg(timeout=10)["content"]["subshell_id"]

    def send(self, code, subshell=None, store_history=True):
        content = dict(code=code, silent=False, store_history=store_history, user_expressions={},
                       allow_stdin=False, stop_on_error=False)
        msg = self.kc.session.msg("execute_request", content)
        if subshell:
            msg["header"]["subshell_id"] = subshell
        self.kc.shell_channel.send(msg)
        return msg["header"]["msg_id"]

    def wait(self, msg_id):
        assert self.idle[msg_id].wait(30)

    def run(self, code, **kwargs):
        msg_id = self.send(code, **kwargs)
        self.wait(msg_id)
        return msg_id

    def stdout(self, msg_id):
        return "".join(m["content"]["text"] for m in self.iopub[msg_id] if m["msg_type"] == "stream")

    def close(self):
        self.stop = True
        self.thread.join()
        self.kc.stop_channels()
        self.km.shutdown_kernel(now=True)

Versions: IPython 9.18.1, ipykernel 7.4.0, jupyter_client 8.10.0, pyzmq 27.3.0, Python 3.13.16, Linux (WSL2). The code involved is unchanged on main as of today.

I found and reduced these while building a tool that drives ipykernel subshells; the investigation and this write-up were done with an AI assistant (🤖🤖). Every output above is pasted from an actual run.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions