Cache separate headers on subshell threads #1414
Merged
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.
This fixes a bug in the caching of received message headers at various places in the code which are later used for reply or iopub messages. The existing code on
main
branch assumes that the shell processes a single request at a time so that the cached header is valid until that request is replied to, but now of course there can be multiple subshells in different threads executing code concurrently.The solution is to cache a different header per subshell, or to be more precise a different header per thread. This is accomplished using a ContextVar which is essentially thread-local storage that also supports asynchronous execution. We are already using a
ContextVar
atipykernel/ipykernel/iostream.py
Line 454 in 4c21800
so it is already a dependency of
ipykernel
.I found this whilst debugging use of
ipympl
injupyterlab
, trying to create multiplematplotlib
plots using the option of one subshell per comm-target (the default option). The best way to view this bug is to use kernelspy as it shows that in this scenerio some messages (e.g. some idle status messages) have the wrong parent header and are therefore displayed in the wrong section of thekernelspy
output.All new
parent_header
attributes are private (leading underscore). Where they were previously public I have added a publicparent_header
getter to extract the appropriate value from theContextVar
so that downstream libraries that have been reading theparent_header
in the main shelll should have the same functionality as before.