From 97fa6918aface933fa960122b4a718bbf51b0f45 Mon Sep 17 00:00:00 2001 From: Pranav Tomar Date: Mon, 30 Nov 2026 00:19:28 +0530 Subject: [PATCH] fix: keep subshell requests from reparenting main-shell thread output Threads started by a main-shell cell have no parent of their own, so their output falls back to the parent of the most recent shell request. That fallback (Kernel._shell_context and the global parent of the shell, display publisher, displayhook and output streams) was updated by set_parent on every thread, so a request handled on a subshell redirected later output of main-shell threads to the subshell request. On a subshell thread, set_parent now only sets the parent for that thread and leaves the fallback to the main shell. Fixes #1603 --- ipykernel/ipkernel.py | 7 +++++- ipykernel/kernelbase.py | 13 +++++++++-- tests/test_subshells.py | 50 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/ipykernel/ipkernel.py b/ipykernel/ipkernel.py index 71b387fab..b093cd4b4 100644 --- a/ipykernel/ipkernel.py +++ b/ipykernel/ipkernel.py @@ -256,7 +256,12 @@ def set_parent(self, ident, parent, channel="shell"): """ super().set_parent(ident, parent, channel) if channel == "shell" and self.shell: - self.shell.set_parent(parent) + if self._in_subshell_thread() and hasattr(self.shell, "set_thread_parent"): + # only set the parent for the subshell thread, keep the global + # fallback used by the main shell's threads unchanged + self.shell.set_thread_parent(parent) + else: + self.shell.set_parent(parent) def init_metadata(self, parent): """Initialize metadata. diff --git a/ipykernel/kernelbase.py b/ipykernel/kernelbase.py index e6705cfc8..31aab4703 100644 --- a/ipykernel/kernelbase.py +++ b/ipykernel/kernelbase.py @@ -21,6 +21,7 @@ from functools import partial from signal import SIGINT, SIGTERM, Signals, default_int_handler, signal +from .subshell import SubshellThread from .thread import CONTROL_THREAD_NAME if sys.platform != "win32": @@ -745,8 +746,16 @@ def set_parent(self, ident, parent, channel="shell"): else: self._shell_parent_ident.set(ident) self._shell_parent.set(parent) - # preserve the last call to set_parent - self._shell_context = copy_context() + if not self._in_subshell_thread(): + # preserve the last call to set_parent on the main shell, used as the + # fallback parent for threads that have no parent of their own. + # Requests handled by a subshell must not redirect that output. + self._shell_context = copy_context() + + @staticmethod + def _in_subshell_thread() -> bool: + """Whether the current thread is a subshell thread""" + return isinstance(threading.current_thread(), SubshellThread) def get_parent(self, channel=None): """Get the parent request associated with a channel. diff --git a/tests/test_subshells.py b/tests/test_subshells.py index 6dcfaec35..8aaf991a0 100644 --- a/tests/test_subshells.py +++ b/tests/test_subshells.py @@ -6,7 +6,7 @@ import platform import time -from collections import Counter +from collections import Counter, defaultdict from queue import Empty import pytest @@ -493,3 +493,51 @@ def test_comm_close_on_deleted_subshell(): kc.shell_channel.send(msg) wait_for_idle(kc, msg["header"]["msg_id"]) + + +def test_subshell_request_does_not_reparent_main_shell_thread_output(): + # A thread started by a main-shell cell has no parent of its own, so its output + # falls back to the most recent main-shell request. A request handled on a + # subshell must not change that fallback (#1603). + with new_kernel() as kc: + subshell_id = create_subshell_helper(kc)["subshell_id"] + flush_channels(kc) + + main_msg = execute_request( + kc, + """import threading +start_thread = threading.Event() +thread_done = threading.Event() +def target(): + start_thread.wait() + print(get_ipython().kernel.get_parent()["header"]["msg_id"], flush=True) + thread_done.set() +threading.Thread(target=target).start() +""", + None, + ) + main_msg_id = main_msg["header"]["msg_id"] + wait_for_idle(kc, main_msg_id) + + # The thread prints while the subshell request is being handled. + sub_msg = execute_request( + kc, f"start_thread.set(); assert thread_done.wait({TIMEOUT})", subshell_id + ) + sub_msg_id = sub_msg["header"]["msg_id"] + stdout: defaultdict[str, str] = defaultdict(str) + while True: + msg = kc.get_iopub_msg(timeout=TIMEOUT) + parent_id = msg["parent_header"].get("msg_id") + if msg["msg_type"] == "stream": + stdout[parent_id] += msg["content"]["text"] + elif msg["msg_type"] == "error": + pytest.fail("\n".join(msg["content"]["traceback"])) + elif ( + msg["msg_type"] == "status" + and msg["content"]["execution_state"] == "idle" + and parent_id == sub_msg_id + ): + break + + assert dict(stdout) == {main_msg_id: main_msg_id + "\n"} + delete_subshell_helper(kc, subshell_id)