Skip to content

Concurrently invoking a ScriptBlock in two runspaces causes InvalidOperationException and pwsh.exe termination #7626

Closed

Description

@alx9r

This came up during #7593 and #7530. I think the circumstances where this can occur is wherever all of the following happen:

  1. A scriptblock from one runspace is passed into another instance of the PowerShell class.
  2. The two PowerShell instances are invoked concurrently.
  3. Each PowerShell instance invokes the scriptblock.

I'm not sure exactly what should happen when invoking a scriptblock that is bound to a SessionState from another runspace. I guess I expected it to be cloned and bound to the session state that it found itself in, similar to scriptblocks produced using ScriptBlock.Create().

This is a rather easy scenario to run into wherever there is interaction between runspaces within a process, though. It seems like at least the crash should be prevented.

Steps to reproduce

$scriptblock = {
    function fibonacci {
        param([int]$n)
        [bigint]$a=0
        [bigint]$b=1
        foreach ($x in 0..$n)
        {
            $a,$b = $b,($a+$b)
        }
        $b
    }
    fibonacci 100000 | % {'complete'}
}

$invocations = 1..2 |
    % {
        $powershell = [powershell]::Create().
            AddScript({. $args[0]}).
            AddArgument($scriptblock)
        @{
            PowerShell = $powershell
            Invocation = $powershell.BeginInvoke()
        }
    }
$invocations |
    %{ $_.PowerShell.EndInvoke($_.Invocation)}

Expected behavior

complete
complete

Actual behavior

This is the most verbose output I have witnessed. The run ended in a "PowerShell Core 6 has stopped working" message box.

complete
% : Stack empty.
At C:\users\un1\Desktop\test.ps1:26 char:5
+     %{ $_.PowerShell.EndInvoke($_.Invocation)}
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [ForEach-Object], InvalidOperationEx
ception
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.
Commands.ForEachObjectCommand


An error has occurred that was not properly handled. Additional information is s
hown below. The PowerShell process will exit.

Unhandled Exception: System.InvalidOperationException: Stack empty.
   at System.Collections.Generic.Stack`1.ThrowForEmptyStack()
   at System.Collections.Generic.Stack`1.Pop()
   at System.Management.Automation.DlrScriptCommandProcessor.OnRestorePreviousSc
ope()
   at System.Management.Automation.CommandProcessorBase.DoComplete()
   at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(Com
mandProcessorBase commandRequestingUpstreamCommandsToStop)
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecute
Enumerate(Object input)
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
   at System.Management.Automation.Runspaces.PipelineThread.WorkerProc()
   at System.Threading.Thread.ThreadMain_ThreadStart()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionCo
ntext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.1.0-preview.4
PSEdition                      Core
GitCommitId                    6.1.0-preview.4
OS                             Microsoft Windows 6.3.9600 
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Activity

  1. added
    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get a
    WG-Enginecore PowerShell engine, interpreter, and runtime
    on Aug 24, 2018
  2. BrucePay commented on Aug 24, 2018

    @BrucePay
    Collaborator

    This is essentially the problem described in #4003. The current expected behavior is for an affinitized scriptblock to be executed in the runspace where it was created. This can only happen if the runspace is otherwise idle so the invocation is posted as an event to be invoked when the runspace becomes available. That said, it's no longer clear that this is the desired behavior. Some history: PSObject affinity was introduced in V1 so that objects returned from the runspace to the calling code could be evaluated by the calling code directly. PSObject affinity included script methods which included scriptblocks. In V2, I added an explicit affinity to scriptblocks so that invoking a scriptblock returned from a module (i.e. a function exported from a module) would execute in the module context. So scriptblocks are tied to modules which are tied to runspaces thus it makes sense to do this cross runspace invocation. However for concurrent operation, this semantic doesn't work since execution ends up serializing on the invoking runspace. This is one of the areas I'm investigating for #6716.

  3. added
    Issue-Enhancementthe issue is more of a feature request than a bug
    and removed
    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get a
    on Jan 30, 2020
  4. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  5. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  6. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  7. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

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

    Issue-Enhancementthe issue is more of a feature request than a bugResolution-No ActivityIssue has had no activity for 6 months or moreWG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions