Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion ipykernel/ipkernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 11 additions & 2 deletions ipykernel/kernelbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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.
Expand Down
50 changes: 49 additions & 1 deletion tests/test_subshells.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import platform
import time
from collections import Counter
from collections import Counter, defaultdict
from queue import Empty

import pytest
Expand Down Expand Up @@ -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)
Loading