From 41747c1cc9617b3975a5657e532d9908b112cf75 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 19:48:47 +0000 Subject: [PATCH 1/5] TEMPORARY: issue #7 diagnostics (trace points, repro workflow) Trace points on the client timeout path and the server's keep-alive and cancellation chain, a workflow that runs the flaky test 30 times per Windows cell plus a timeout sweep. Removed again before the fix PR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012kC9BM7EcqLbLxn8DocWHe --- .github/workflows/repro-issue7.yml | 52 ++++++++++++++++++++ src/Private/Dispatcher.ps1 | 2 + src/Private/HttpClient.ps1 | 6 +++ src/Private/HttpServer.ps1 | 4 ++ src/Private/ReproTrace.ps1 | 12 +++++ tests/Integration/HttpServer.Tests.ps1 | 13 ++++- tools/repro/Invoke-Issue7Repro.ps1 | 59 +++++++++++++++++++++++ tools/repro/Invoke-Issue7Sweep.ps1 | 67 ++++++++++++++++++++++++++ 8 files changed, 214 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/repro-issue7.yml create mode 100644 src/Private/ReproTrace.ps1 create mode 100644 tools/repro/Invoke-Issue7Repro.ps1 create mode 100644 tools/repro/Invoke-Issue7Sweep.ps1 diff --git a/.github/workflows/repro-issue7.yml b/.github/workflows/repro-issue7.yml new file mode 100644 index 0000000..bcddfc0 --- /dev/null +++ b/.github/workflows/repro-issue7.yml @@ -0,0 +1,52 @@ +# TEMPORARY (issue #7): repeated runs of the flaky HTTP cancellation test; removed before the fix PR. +name: Repro issue 7 + +on: + push: + branches: [claude/vigilant-shannon-oubi04] + +permissions: + contents: read + +env: + POWERSHELL_TELEMETRY_OPTOUT: '1' + DOTNET_CLI_TELEMETRY_OPTOUT: '1' + DOTNET_NOLOGO: '1' + +jobs: + repro: + name: Repro (${{ matrix.os }}, pwsh ${{ matrix.pwsh }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + os: [windows-latest] + pwsh: ['7.4.20', '7.5.11', '7.6.6'] + include: + - os: ubuntu-latest + pwsh: '7.6.6' + steps: + - name: Check out + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Install PowerShell ${{ matrix.pwsh }} + uses: ./.github/actions/install-pwsh + with: + version: ${{ matrix.pwsh }} + - name: Build + shell: pwsh + run: ./build.ps1 -Bootstrap -Task Build + - name: Repeated test runs + shell: pwsh + run: ./tools/repro/Invoke-Issue7Repro.ps1 -Iterations 30 + - name: Timeout sweep + if: always() + shell: pwsh + run: ./tools/repro/Invoke-Issue7Sweep.ps1 + - name: Upload traces + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: repro-${{ matrix.os }}-pwsh${{ matrix.pwsh }} + path: output/repro/ + if-no-files-found: warn diff --git a/src/Private/Dispatcher.ps1 b/src/Private/Dispatcher.ps1 index 65cf4fd..6671d99 100644 --- a/src/Private/Dispatcher.ps1 +++ b/src/Private/Dispatcher.ps1 @@ -360,6 +360,7 @@ function Stop-McpInFlightRequest { ) $Entry.Cancelled = $true + Write-McpReproTrace "server id=$($Entry.Id) Stop-McpInFlightRequest (Cts.Cancel + BeginStop)" try { $Entry.Cts.Cancel() } catch { Write-Debug 'Cancelling the request token failed.' } try { $null = $Entry.PowerShell.BeginStop($null, $null) } catch { Write-Debug 'Stopping the worker pipeline failed.' } } @@ -435,6 +436,7 @@ function Update-McpInFlightRequest { } continue } + Write-McpReproTrace "server id=$($entry.Id) worker finished: $invocationState (cancelled=$($entry.Cancelled), responded=$($entry.Responded))" # A worker enqueues its response before it completes: deliver whatever is queued while the entry exists. Send-McpOutboundQueue -State $State if ($invocationState -eq [System.Management.Automation.PSInvocationState]::Failed -and -not $entry.Cancelled -and -not $entry.Responded) { diff --git a/src/Private/HttpClient.ps1 b/src/Private/HttpClient.ps1 index b75d40a..c2d8ae4 100644 --- a/src/Private/HttpClient.ps1 +++ b/src/Private/HttpClient.ps1 @@ -293,6 +293,7 @@ function Receive-McpSseResponse { while ($true) { $remaining = ($Deadline - [datetime]::UtcNow).TotalMilliseconds if ($remaining -le 0) { + Write-McpReproTrace "client id=$Id SSE read timeout; disposing the reader" $Cts.Cancel() throw [System.TimeoutException]::new("No response to '$Method' (id $Id) within the timeout; the response stream was closed, which cancels the request.") } @@ -569,7 +570,11 @@ function Invoke-McpHttpClientRequest { $tick = if ($Session.Era -eq 'Legacy') { { Invoke-McpLegacyInbox -Session $Session } } else { $null } $sendTask = $transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cts.Token) if (-not (Wait-McpTask -Task $sendTask -Deadline $deadline -OnTick $tick)) { + Write-McpReproTrace "client id=$id header timeout; sendTask before Cancel: $($sendTask.Status)" $cts.Cancel() + Write-McpReproTrace "client id=$id sendTask after Cancel: $($sendTask.Status)" + try { $null = $sendTask.Wait(200) } catch { Write-Debug 'ignored' } + Write-McpReproTrace "client id=$id sendTask 200 ms after Cancel: $($sendTask.Status)$(if ($sendTask.Status -eq 'RanToCompletion') { ' -> LEAKED RESPONSE (never disposed)' })" throw [System.TimeoutException]::new("No response headers from $($transport.Url) for '$Method' (id $id) within $TimeoutMs ms.") } $failure = Get-McpTaskFailure -Task $sendTask @@ -594,6 +599,7 @@ function Invoke-McpHttpClientRequest { $mediaType = $null if ($null -ne $response.Content -and $null -ne $response.Content.Headers.ContentType) { $mediaType = $response.Content.Headers.ContentType.MediaType } Write-Debug "<- HTTP $status $mediaType for $Method id=$id" + Write-McpReproTrace "client id=$id headers received: HTTP $status $mediaType ($([int] ($deadline - [datetime]::UtcNow).TotalMilliseconds) ms before deadline)" if ($mediaType -eq 'text/event-stream') { return Receive-McpSseResponse -Session $Session -Response $response -Id $id -Method $Method -Deadline $deadline -Cts $cts -ProgressToken $progressToken -OnProgress $OnProgress } diff --git a/src/Private/HttpServer.ps1 b/src/Private/HttpServer.ps1 index 639c74e..2675a06 100644 --- a/src/Private/HttpServer.ps1 +++ b/src/Private/HttpServer.ps1 @@ -370,6 +370,7 @@ function Start-McpHttpSse { $Channel.Mode = 'Sse' $Channel.LastWrite = [datetime]::UtcNow $State.Transport.OpenChannels.Add($Channel) + Write-McpReproTrace "server id=$($Channel.RequestId) switched to SSE" Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message ("-> HTTP 200 text/event-stream id={0}" -f $Channel.RequestId) return $true } catch { @@ -399,8 +400,10 @@ function Write-McpSseChunk { $Channel.Stream.Write($bytes, 0, $bytes.Length) $Channel.Stream.Flush() $Channel.LastWrite = [datetime]::UtcNow + if ($Text.StartsWith(':')) { Write-McpReproTrace "server id=$($Channel.RequestId) keep-alive write OK" } return $true } catch { + Write-McpReproTrace "server id=$($Channel.RequestId) SSE write FAILED: $($_.Exception.GetType().FullName): $($_.Exception.Message)" Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Writing to an SSE stream failed (id=$($Channel.RequestId)): $($_.Exception.Message)" Close-McpHttpChannel -State $State -Channel $Channel -Abort return $false @@ -525,6 +528,7 @@ function Stop-McpHttpChannelRequest { $entry = $State.InFlight[$key] if ($entry.Cancelled -or $entry.Responded) { return } Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.Label)): the client closed the connection; cancelling." + Write-McpReproTrace "server id=$($entry.Id) Stop-McpHttpChannelRequest -> cancelling" Stop-McpInFlightRequest -Entry $entry $entry.Responded = $true } diff --git a/src/Private/ReproTrace.ps1 b/src/Private/ReproTrace.ps1 new file mode 100644 index 0000000..157c40e --- /dev/null +++ b/src/Private/ReproTrace.ps1 @@ -0,0 +1,12 @@ +# TEMPORARY (issue #7 diagnostics): appends a timestamped line to $env:MCP_REPRO_LOG when it is set. +function Write-McpReproTrace { + [CmdletBinding()] + param([Parameter(Mandatory)][string] $Message) + + $path = $env:MCP_REPRO_LOG + if (-not $path) { return } + $line = '{0} [t{1}] {2}{3}' -f [datetime]::UtcNow.ToString('HH:mm:ss.fff', [System.Globalization.CultureInfo]::InvariantCulture), [System.Threading.Thread]::CurrentThread.ManagedThreadId, $Message, [Environment]::NewLine + for ($attempt = 0; $attempt -lt 5; $attempt++) { + try { [System.IO.File]::AppendAllText($path, $line); return } catch { [System.Threading.Thread]::Sleep(2) } + } +} diff --git a/tests/Integration/HttpServer.Tests.ps1 b/tests/Integration/HttpServer.Tests.ps1 index c0ad26b..d335673 100644 --- a/tests/Integration/HttpServer.Tests.ps1 +++ b/tests/Integration/HttpServer.Tests.ps1 @@ -105,7 +105,18 @@ Describe 'Connect-McpServer over Streamable HTTP' -Tag 'Integration' { { Invoke-McpTool -Name 'count' -Arguments @{ To = 200; DelayMs = 50; MarkerPath = $marker } -TimeoutSeconds 1 -Session $script:session } | Should -Throw -ExceptionType ([System.TimeoutException]) (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'alive' } -Session $script:session).Text | Should -Be 'alive' $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - while (-not (Test-Path -Path $marker) -and $stopwatch.Elapsed.TotalSeconds -lt 8) { Start-Sleep -Milliseconds 100 } + # TEMPORARY (issue #7 diagnostics): TCP states of the loopback connections to the server port. + $nextSnapshot = 0 + while (-not (Test-Path -Path $marker) -and $stopwatch.Elapsed.TotalSeconds -lt 8) { + if ($env:MCP_REPRO_LOG -and $IsWindows -and $stopwatch.Elapsed.TotalSeconds -ge $nextSnapshot) { + $nextSnapshot += 1 + $port = $script:handle.Port + $rows = @(Get-NetTCPConnection -ErrorAction SilentlyContinue | Where-Object { $_.LocalPort -eq $port -or $_.RemotePort -eq $port } | ForEach-Object { '{0}:{1}->{2}:{3} {4} pid={5}' -f $_.LocalAddress, $_.LocalPort, $_.RemoteAddress, $_.RemotePort, $_.State, $_.OwningProcess }) + [System.IO.File]::AppendAllText($env:MCP_REPRO_LOG, ('{0} test tcp@{1:n1}s: {2}{3}' -f [datetime]::UtcNow.ToString('HH:mm:ss.fff'), $stopwatch.Elapsed.TotalSeconds, ($rows -join ' | '), [Environment]::NewLine)) + } + Start-Sleep -Milliseconds 100 + } + if ($env:MCP_REPRO_LOG) { [System.IO.File]::AppendAllText($env:MCP_REPRO_LOG, ('{0} test marker after {1:n1}s: {2}{3}' -f [datetime]::UtcNow.ToString('HH:mm:ss.fff'), $stopwatch.Elapsed.TotalSeconds, $(if (Test-Path $marker) { [System.IO.File]::ReadAllText($marker) } else { 'MISSING' }), [Environment]::NewLine)) } Test-Path -Path $marker | Should -BeTrue $text = [System.IO.File]::ReadAllText($marker) $text | Should -Match '^stopped at (\d+) of 200$' diff --git a/tools/repro/Invoke-Issue7Repro.ps1 b/tools/repro/Invoke-Issue7Repro.ps1 new file mode 100644 index 0000000..c438d3b --- /dev/null +++ b/tools/repro/Invoke-Issue7Repro.ps1 @@ -0,0 +1,59 @@ +# TEMPORARY (issue #7): runs the flaky integration test N times in fresh processes and classifies each run from +# the trace written by the instrumented module ($env:MCP_REPRO_LOG). Requires a built module under output/. +[CmdletBinding()] +param( + [int] $Iterations = 30, + [string] $LogDirectory = (Join-Path $PSScriptRoot '..' '..' 'output' 'repro'), + [string] $FullName = '*stops the handler when the client closes the connection on timeout*' +) + +$ErrorActionPreference = 'Stop' +$null = New-Item -ItemType Directory -Path $LogDirectory -Force +$LogDirectory = (Resolve-Path $LogDirectory).Path +$testFile = (Resolve-Path (Join-Path $PSScriptRoot '..' '..' 'tests' 'Integration' 'HttpServer.Tests.ps1')).Path +$pwsh = (Get-Process -Id $PID).Path +$rows = [System.Collections.Generic.List[object]]::new() +for ($i = 1; $i -le $Iterations; $i++) { + $log = Join-Path $LogDirectory ('run-{0:d2}.log' -f $i) + $env:MCP_REPRO_LOG = $log + $script = @" +Import-Module Pester -MinimumVersion 6.2.0 +`$c = New-PesterConfiguration +`$c.Run.Path = '$testFile' +`$c.Run.PassThru = `$true +`$c.Filter.FullName = '$FullName' +`$c.Output.Verbosity = 'Normal' +`$r = Invoke-Pester -Configuration `$c +if (`$r.PassedCount -eq 1 -and `$r.FailedCount -eq 0) { exit 0 } else { exit 1 } +"@ + $output = & $pwsh -NoLogo -NoProfile -NonInteractive -Command $script 2>&1 + $passed = $LASTEXITCODE -eq 0 + $text = if (Test-Path $log) { Get-Content -Raw $log } else { '' } + $leak = $text -match 'LEAKED RESPONSE' + $headerTimeout = $text -match 'header timeout' + $sseTimeout = $text -match 'SSE read timeout' + $writeFailed = $text -match 'SSE write FAILED' + $keepAlives = ([regex]::Matches($text, 'keep-alive write OK')).Count + $marker = if ($text -match 'test marker after [^:]+: (.*)') { $Matches[1].Trim() } else { '?' } + $row = [pscustomobject]@{ + Run = $i; Passed = $passed; ClientPath = $(if ($headerTimeout) { 'header-timeout' } elseif ($sseTimeout) { 'sse-timeout' } else { '?' }) + Leak = $leak; KeepAliveOk = $keepAlives; WriteFailed = $writeFailed; Marker = $marker + } + $rows.Add($row) + $row | Format-Table -HideTableHeaders | Out-String | Write-Host + if (-not $passed) { + Write-Host "---- run $i FAILED; Pester output ----" + $output | Select-Object -Last 40 | ForEach-Object { Write-Host $_ } + Write-Host "---- run $i trace ----" + Write-Host $text + } +} +Remove-Item Env:MCP_REPRO_LOG +$failed = @($rows | Where-Object { -not $_.Passed }).Count +$summary = @( + "## Issue #7 repro: $($PSVersionTable.OS), pwsh $($PSVersionTable.PSVersion)", '', + "Failures: **$failed / $Iterations**; leaked responses: $(@($rows | Where-Object Leak).Count)", '', + '| Run | Passed | Client path | Leak | Keep-alives OK | Write failed | Marker |', '|---|---|---|---|---|---|---|' +) + ($rows | ForEach-Object { '| {0} | {1} | {2} | {3} | {4} | {5} | {6} |' -f $_.Run, $_.Passed, $_.ClientPath, $_.Leak, $_.KeepAliveOk, $_.WriteFailed, $_.Marker }) +if ($env:GITHUB_STEP_SUMMARY) { $summary | Add-Content -Path $env:GITHUB_STEP_SUMMARY } +$summary | Write-Host diff --git a/tools/repro/Invoke-Issue7Sweep.ps1 b/tools/repro/Invoke-Issue7Sweep.ps1 new file mode 100644 index 0000000..45c3755 --- /dev/null +++ b/tools/repro/Invoke-Issue7Sweep.ps1 @@ -0,0 +1,67 @@ +# TEMPORARY (issue #7): sweeps the client timeout across the server's switch to SSE (KeepAliveSeconds = 1) so +# that the response headers arrive around the client deadline, and checks after each call whether the server +# stopped the handler. Platform independent; requires a built module under output/. +[CmdletBinding()] +param( + [int] $FromMs = 950, + [int] $ToMs = 1300, + [int] $StepMs = 10, + [string] $LogPath = (Join-Path $PSScriptRoot '..' '..' 'output' 'repro' 'sweep.log') +) + +$ErrorActionPreference = 'Stop' +$root = Join-Path $PSScriptRoot '..' '..' +Import-Module (Join-Path $root 'tests' 'Support' 'McpTestSupport.psm1') -Force +Import-Module (Get-McpBuiltModuleManifest) -Force +$null = New-Item -ItemType Directory -Path (Split-Path $LogPath) -Force +$env:MCP_REPRO_LOG = $LogPath +$server = New-McpServer -Name 'sweep' -Version '1.0.0' -RequestTimeoutSeconds 30 +Register-McpTool -Name 'count' -Description 'Counts; a marker file records where it stopped.' -ScriptBlock { + param([int] $To = 3, [int] $DelayMs = 20, [string] $MarkerPath = '', $Context) + $i = 0 + try { + for ($i = 1; $i -le $To; $i++) { + if ($Context.CancellationToken.IsCancellationRequested) { return "cancelled at $i" } + Start-Sleep -Milliseconds $DelayMs + } + "counted to $To" + } finally { + if ($MarkerPath) { [System.IO.File]::WriteAllText($MarkerPath, "stopped at $i of $To") } + } +} -Server $server +$handle = Start-McpTestHttpServer -Server $server -Parameters @{ KeepAliveSeconds = 1 } +$session = Connect-McpServer -Url $handle.Url +$module = Get-Module -Name ModelContextProtocol +$rows = [System.Collections.Generic.List[object]]::new() +try { + for ($timeout = $FromMs; $timeout -le $ToMs; $timeout += $StepMs) { + $marker = Join-Path ([System.IO.Path]::GetTempPath()) ('mcp-sweep-' + [guid]::NewGuid().ToString('n') + '.txt') + $params = [ordered]@{ name = 'count'; arguments = [ordered]@{ To = 200; DelayMs = 50; MarkerPath = $marker } } + $outcome = 'no timeout' + try { + $null = & $module { param($s, $p, $t) Invoke-McpHttpClientRequest -Session $s -Method 'tools/call' -Params $p -TimeoutMs $t } $session $params $timeout + } catch [System.TimeoutException] { + $outcome = 'timeout' + } + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + while (-not (Test-Path -Path $marker) -and $stopwatch.Elapsed.TotalSeconds -lt 8) { Start-Sleep -Milliseconds 50 } + $text = if (Test-Path $marker) { [System.IO.File]::ReadAllText($marker) } else { 'MISSING' } + $stopped = $text -match '^stopped at (\d+) of 200$' -and [int] $Matches[1] -lt 150 + $rows.Add([pscustomobject]@{ TimeoutMs = $timeout; Client = $outcome; StoppedAfterS = [math]::Round($stopwatch.Elapsed.TotalSeconds, 1); Marker = $text; Ok = $stopped }) + Remove-Item -Path $marker -ErrorAction SilentlyContinue + } +} finally { + Disconnect-McpServer -Session $session + Stop-McpTestHttpServer -Handle $handle + Remove-Item Env:MCP_REPRO_LOG +} +$trace = Get-Content -Raw $LogPath +$leaks = ([regex]::Matches($trace, 'LEAKED RESPONSE')).Count +$bad = @($rows | Where-Object { -not $_.Ok }).Count +$summary = @( + "## Issue #7 timeout sweep: $($PSVersionTable.OS), pwsh $($PSVersionTable.PSVersion)", '', + "Handler not stopped: **$bad / $($rows.Count)**; leaked responses in the trace: $leaks", '', + '| Timeout (ms) | Client | Marker after (s) | Marker | OK |', '|---|---|---|---|---|' +) + ($rows | ForEach-Object { '| {0} | {1} | {2} | {3} | {4} |' -f $_.TimeoutMs, $_.Client, $_.StoppedAfterS, $_.Marker, $_.Ok }) +if ($env:GITHUB_STEP_SUMMARY) { $summary | Add-Content -Path $env:GITHUB_STEP_SUMMARY } +$summary | Write-Host From a6dc2d3f845b621b069a9f529c5a444771aa2f59 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 19:51:03 +0000 Subject: [PATCH 2/5] Dispose a response that arrives while a timed-out send is cancelled When the response headers arrived between the client's deadline check and the cancellation, SendAsync completed anyway and its HttpResponseMessage was never disposed. The connection stayed open, the server's keep-alive writes kept succeeding, and the server never learned that the client had given up, so the handler ran to completion (issue #7). Stop-McpHttpSendTask cancels, lets the send settle and disposes a late response; it replaces the bare Cancel() at the three timeout sites. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012kC9BM7EcqLbLxn8DocWHe --- src/Private/HttpClient.ps1 | 41 +++++++++++++++++++++++++----- tests/Unit/HttpClient.Tests.ps1 | 45 +++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 tests/Unit/HttpClient.Tests.ps1 diff --git a/src/Private/HttpClient.ps1 b/src/Private/HttpClient.ps1 index c2d8ae4..0ebc4ff 100644 --- a/src/Private/HttpClient.ps1 +++ b/src/Private/HttpClient.ps1 @@ -93,6 +93,37 @@ function Wait-McpTask { $true } +function Stop-McpHttpSendTask { + <# + .SYNOPSIS + Cancels a send that missed its deadline and disposes its response should the send complete anyway. + .DESCRIPTION + Cancelling cannot undo a send whose response headers arrived just before the cancellation: the task then + completes with a response, and its connection stays open until that response is disposed. The server + detects a client that gave up only through a failing write, which an open connection never produces. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Internal request bookkeeping.')] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Threading.Tasks.Task] $Task, + + [Parameter(Mandatory)] + [System.Threading.CancellationTokenSource] $Cts, + + # How long a cancelled send may take to settle; it ends at once unless the connection is stuck. + [int] $SettleMs = 1000 + ) + + try { $Cts.Cancel() } catch { Write-Debug 'Cancelling the send failed.' } + if (-not $Task.IsCompleted) { + try { $null = $Task.Wait($SettleMs) } catch [System.AggregateException] { Write-Debug 'The cancelled send ended with an error.' } + } + if ($Task.Status -eq [System.Threading.Tasks.TaskStatus]::RanToCompletion -and $null -ne $Task.Result) { + try { $Task.Result.Dispose() } catch { Write-Debug 'Disposing the late response failed.' } + } +} + function Get-McpTaskFailure { [CmdletBinding()] [OutputType([System.Exception], [System.OperationCanceledException])] @@ -450,7 +481,7 @@ function Open-McpHttpResumedStream { Write-Debug "-> GET $($Session.Transport.Url) Last-Event-ID $LastEventId (resuming '$Method' id=$Id)" $task = $Session.Transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $Cts.Token) if (-not (Wait-McpTask -Task $task -Deadline $Deadline)) { - $Cts.Cancel() + Stop-McpHttpSendTask -Task $task -Cts $Cts throw [System.TimeoutException]::new("Resuming the response stream of '$Method' (id $Id) timed out.") } $failure = Get-McpTaskFailure -Task $task @@ -571,10 +602,8 @@ function Invoke-McpHttpClientRequest { $sendTask = $transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cts.Token) if (-not (Wait-McpTask -Task $sendTask -Deadline $deadline -OnTick $tick)) { Write-McpReproTrace "client id=$id header timeout; sendTask before Cancel: $($sendTask.Status)" - $cts.Cancel() - Write-McpReproTrace "client id=$id sendTask after Cancel: $($sendTask.Status)" - try { $null = $sendTask.Wait(200) } catch { Write-Debug 'ignored' } - Write-McpReproTrace "client id=$id sendTask 200 ms after Cancel: $($sendTask.Status)$(if ($sendTask.Status -eq 'RanToCompletion') { ' -> LEAKED RESPONSE (never disposed)' })" + Stop-McpHttpSendTask -Task $sendTask -Cts $cts + Write-McpReproTrace "client id=$id sendTask after Stop-McpHttpSendTask: $($sendTask.Status)$(if ($sendTask.Status -eq 'RanToCompletion') { ' -> late response DISPOSED (fix path)' })" throw [System.TimeoutException]::new("No response headers from $($transport.Url) for '$Method' (id $id) within $TimeoutMs ms.") } $failure = Get-McpTaskFailure -Task $sendTask @@ -672,7 +701,7 @@ function Send-McpHttpClientMessage { try { $sendTask = $transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseContentRead, $cts.Token) if (-not (Wait-McpTask -Task $sendTask -Deadline ([datetime]::UtcNow.AddMilliseconds($TimeoutMs)))) { - $cts.Cancel() + Stop-McpHttpSendTask -Task $sendTask -Cts $cts throw [System.TimeoutException]::new("Posting the notification '$Method' timed out after $TimeoutMs ms.") } $failure = Get-McpTaskFailure -Task $sendTask diff --git a/tests/Unit/HttpClient.Tests.ps1 b/tests/Unit/HttpClient.Tests.ps1 new file mode 100644 index 0000000..1a6528f --- /dev/null +++ b/tests/Unit/HttpClient.Tests.ps1 @@ -0,0 +1,45 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseCorrectCasing', '', Justification = 'PSScriptAnalyzer attributes -ScriptBlock of commands nested in BeforeAll to BeforeAll itself.')] +param() + +BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..' 'Support' 'McpTestSupport.psm1') -Force + Import-Module (Get-McpBuiltModuleManifest) -Force +} + +Describe 'Stop-McpHttpSendTask' { + It 'disposes the response of a send that completed although it was cancelled' { + # The response headers arrived between the deadline and the cancellation: the task completed anyway. + $body = [System.IO.MemoryStream]::new([byte[]] @(1, 2, 3)) + $response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::OK) + $response.Content = [System.Net.Http.StreamContent]::new($body) + $task = [System.Threading.Tasks.Task]::FromResult($response) + $cts = [System.Threading.CancellationTokenSource]::new() + Invoke-McpInModule { param($t, $c) Stop-McpHttpSendTask -Task $t -Cts $c } -Parameters @{ t = $task; c = $cts } + $cts.IsCancellationRequested | Should -BeTrue + $body.CanRead | Should -BeFalse + } + + It 'cancels a pending send and returns once it settled' { + $source = [System.Threading.Tasks.TaskCompletionSource[System.Net.Http.HttpResponseMessage]]::new() + $cts = [System.Threading.CancellationTokenSource]::new() + $null = $cts.Token.Register([System.Action] { $null = $source.TrySetCanceled() }.GetNewClosure()) + { Invoke-McpInModule { param($t, $c) Stop-McpHttpSendTask -Task $t -Cts $c } -Parameters @{ t = $source.Task; c = $cts } } | Should -Not -Throw + $source.Task.IsCanceled | Should -BeTrue + } + + It 'tolerates a failed send and a disposed token source' { + $failed = [System.Threading.Tasks.Task]::FromException([System.Net.Http.HttpRequestException]::new('refused')) + $cts = [System.Threading.CancellationTokenSource]::new() + $cts.Dispose() + { Invoke-McpInModule { param($t, $c) Stop-McpHttpSendTask -Task $t -Cts $c } -Parameters @{ t = $failed; c = $cts } } | Should -Not -Throw + } + + It 'returns after the settle time when a send never ends' { + $source = [System.Threading.Tasks.TaskCompletionSource[System.Net.Http.HttpResponseMessage]]::new() + $cts = [System.Threading.CancellationTokenSource]::new() + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + Invoke-McpInModule { param($t, $c) Stop-McpHttpSendTask -Task $t -Cts $c -SettleMs 100 } -Parameters @{ t = $source.Task; c = $cts } + $stopwatch.ElapsedMilliseconds | Should -BeLessThan 2000 + $source.Task.IsCompleted | Should -BeFalse + } +} From 85b5f16b4020c77e770a88e6cd25cb88da98efbc Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 19:57:55 +0000 Subject: [PATCH 3/5] TEMPORARY: issue #7 diagnostics in suite context Runs the whole HttpServer test file and Unit plus that file repeatedly, traces slow dispatcher ticks, and can switch the client fix off (MCP_REPRO_NOFIX) to measure the baseline. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012kC9BM7EcqLbLxn8DocWHe --- .github/workflows/repro-issue7.yml | 20 ++++++++++--------- src/Private/HttpClient.ps1 | 1 + src/Private/HttpServer.ps1 | 3 +++ tools/repro/Invoke-Issue7Repro.ps1 | 32 +++++++++++++++++++----------- 4 files changed, 35 insertions(+), 21 deletions(-) diff --git a/.github/workflows/repro-issue7.yml b/.github/workflows/repro-issue7.yml index bcddfc0..4528460 100644 --- a/.github/workflows/repro-issue7.yml +++ b/.github/workflows/repro-issue7.yml @@ -15,7 +15,7 @@ env: jobs: repro: - name: Repro (${{ matrix.os }}, pwsh ${{ matrix.pwsh }}) + name: Repro (${{ matrix.os }}, pwsh ${{ matrix.pwsh }}, nofix=${{ matrix.nofix }}) runs-on: ${{ matrix.os }} timeout-minutes: 45 strategy: @@ -23,9 +23,7 @@ jobs: matrix: os: [windows-latest] pwsh: ['7.4.20', '7.5.11', '7.6.6'] - include: - - os: ubuntu-latest - pwsh: '7.6.6' + nofix: ['1'] steps: - name: Check out uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -36,17 +34,21 @@ jobs: - name: Build shell: pwsh run: ./build.ps1 -Bootstrap -Task Build - - name: Repeated test runs + - name: Whole HttpServer.Tests.ps1, 30 runs shell: pwsh - run: ./tools/repro/Invoke-Issue7Repro.ps1 -Iterations 30 - - name: Timeout sweep + env: + MCP_REPRO_NOFIX: ${{ matrix.nofix }} + run: ./tools/repro/Invoke-Issue7Repro.ps1 -Iterations 30 -WholeFiles + - name: Unit tests plus HttpServer.Tests.ps1, 8 runs if: always() shell: pwsh - run: ./tools/repro/Invoke-Issue7Sweep.ps1 + env: + MCP_REPRO_NOFIX: ${{ matrix.nofix }} + run: ./tools/repro/Invoke-Issue7Repro.ps1 -Iterations 8 -WholeFiles -Path Unit, Integration/HttpServer.Tests.ps1 -LogDirectory output/repro/suite - name: Upload traces if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: repro-${{ matrix.os }}-pwsh${{ matrix.pwsh }} + name: repro-${{ matrix.os }}-pwsh${{ matrix.pwsh }}-nofix${{ matrix.nofix }} path: output/repro/ if-no-files-found: warn diff --git a/src/Private/HttpClient.ps1 b/src/Private/HttpClient.ps1 index 0ebc4ff..308ceb1 100644 --- a/src/Private/HttpClient.ps1 +++ b/src/Private/HttpClient.ps1 @@ -116,6 +116,7 @@ function Stop-McpHttpSendTask { ) try { $Cts.Cancel() } catch { Write-Debug 'Cancelling the send failed.' } + if ($env:MCP_REPRO_NOFIX) { return } # TEMPORARY (issue #7 baseline) if (-not $Task.IsCompleted) { try { $null = $Task.Wait($SettleMs) } catch [System.AggregateException] { Write-Debug 'The cancelled send ended with an error.' } } diff --git a/src/Private/HttpServer.ps1 b/src/Private/HttpServer.ps1 index 2675a06..d4c6f22 100644 --- a/src/Private/HttpServer.ps1 +++ b/src/Private/HttpServer.ps1 @@ -940,7 +940,10 @@ function Invoke-McpHttpDispatcherLoop { $listener = $transport.Listener $acceptTask = $listener.GetContextAsync() $stopDeadline = $null + $reproTick = [System.Diagnostics.Stopwatch]::StartNew() while ($true) { + if ($reproTick.ElapsedMilliseconds -gt 400) { Write-McpReproTrace "server dispatcher tick took $($reproTick.ElapsedMilliseconds) ms (in flight: $($State.InFlight.Count), open channels: $($transport.OpenChannels.Count))" } + $reproTick.Restart() $handles = [System.Collections.Generic.List[System.Threading.WaitHandle]]::new() if (-not $transport.Stopped) { $handles.Add((Get-McpTaskWaitHandle -Task $acceptTask)) } $handles.Add($State.Signal) diff --git a/tools/repro/Invoke-Issue7Repro.ps1 b/tools/repro/Invoke-Issue7Repro.ps1 index c438d3b..f39e0a2 100644 --- a/tools/repro/Invoke-Issue7Repro.ps1 +++ b/tools/repro/Invoke-Issue7Repro.ps1 @@ -4,27 +4,31 @@ param( [int] $Iterations = 30, [string] $LogDirectory = (Join-Path $PSScriptRoot '..' '..' 'output' 'repro'), - [string] $FullName = '*stops the handler when the client closes the connection on timeout*' + [string] $FullName = '*stops the handler when the client closes the connection on timeout*', + # Test files relative to tests/; the default runs only the flaky test's file. + [string[]] $Path = @('Integration/HttpServer.Tests.ps1'), + [switch] $WholeFiles ) $ErrorActionPreference = 'Stop' $null = New-Item -ItemType Directory -Path $LogDirectory -Force $LogDirectory = (Resolve-Path $LogDirectory).Path -$testFile = (Resolve-Path (Join-Path $PSScriptRoot '..' '..' 'tests' 'Integration' 'HttpServer.Tests.ps1')).Path +$testFiles = ($Path | ForEach-Object { "'" + (Resolve-Path (Join-Path $PSScriptRoot '..' '..' 'tests' $_)).Path + "'" }) -join ',' $pwsh = (Get-Process -Id $PID).Path $rows = [System.Collections.Generic.List[object]]::new() for ($i = 1; $i -le $Iterations; $i++) { - $log = Join-Path $LogDirectory ('run-{0:d2}.log' -f $i) + $log = Join-Path $LogDirectory ('{0}-run-{1:d2}.log' -f $(if ($WholeFiles) { 'files' } else { 'single' }), $i) $env:MCP_REPRO_LOG = $log $script = @" Import-Module Pester -MinimumVersion 6.2.0 `$c = New-PesterConfiguration -`$c.Run.Path = '$testFile' +`$c.Run.Path = @($testFiles) `$c.Run.PassThru = `$true -`$c.Filter.FullName = '$FullName' +if (-not `$$([bool] $WholeFiles)) { `$c.Filter.FullName = '$FullName' } `$c.Output.Verbosity = 'Normal' `$r = Invoke-Pester -Configuration `$c -if (`$r.PassedCount -eq 1 -and `$r.FailedCount -eq 0) { exit 0 } else { exit 1 } +`$r.Failed | ForEach-Object { 'FAILED TEST: ' + `$_.ExpandedPath } +if (`$r.PassedCount -ge 1 -and `$r.FailedCount -eq 0) { exit 0 } else { exit 1 } "@ $output = & $pwsh -NoLogo -NoProfile -NonInteractive -Command $script 2>&1 $passed = $LASTEXITCODE -eq 0 @@ -34,26 +38,30 @@ if (`$r.PassedCount -eq 1 -and `$r.FailedCount -eq 0) { exit 0 } else { exit 1 } $sseTimeout = $text -match 'SSE read timeout' $writeFailed = $text -match 'SSE write FAILED' $keepAlives = ([regex]::Matches($text, 'keep-alive write OK')).Count + $slowTicks = ([regex]::Matches($text, 'dispatcher tick took')).Count $marker = if ($text -match 'test marker after [^:]+: (.*)') { $Matches[1].Trim() } else { '?' } $row = [pscustomobject]@{ Run = $i; Passed = $passed; ClientPath = $(if ($headerTimeout) { 'header-timeout' } elseif ($sseTimeout) { 'sse-timeout' } else { '?' }) - Leak = $leak; KeepAliveOk = $keepAlives; WriteFailed = $writeFailed; Marker = $marker + Leak = $leak; KeepAliveOk = $keepAlives; SlowTicks = $slowTicks; WriteFailed = $writeFailed; Marker = $marker } $rows.Add($row) $row | Format-Table -HideTableHeaders | Out-String | Write-Host if (-not $passed) { Write-Host "---- run $i FAILED; Pester output ----" $output | Select-Object -Last 40 | ForEach-Object { Write-Host $_ } - Write-Host "---- run $i trace ----" - Write-Host $text + Write-Host "---- run $i trace (timeout test window) ----" + $lines = $text -split "`r?`n" + $start = [array]::FindIndex($lines, [Predicate[string]] { param($l) $l -match 'header timeout|SSE read timeout' }) + if ($start -lt 0) { $start = 0 } + $lines[[math]::Max(0, $start - 5)..[math]::Min($lines.Count - 1, $start + 120)] | ForEach-Object { Write-Host $_ } } } Remove-Item Env:MCP_REPRO_LOG $failed = @($rows | Where-Object { -not $_.Passed }).Count $summary = @( - "## Issue #7 repro: $($PSVersionTable.OS), pwsh $($PSVersionTable.PSVersion)", '', + "## Issue #7 repro ($($Path -join ', '), whole files: $([bool] $WholeFiles)): $($PSVersionTable.OS), pwsh $($PSVersionTable.PSVersion)", '', "Failures: **$failed / $Iterations**; leaked responses: $(@($rows | Where-Object Leak).Count)", '', - '| Run | Passed | Client path | Leak | Keep-alives OK | Write failed | Marker |', '|---|---|---|---|---|---|---|' -) + ($rows | ForEach-Object { '| {0} | {1} | {2} | {3} | {4} | {5} | {6} |' -f $_.Run, $_.Passed, $_.ClientPath, $_.Leak, $_.KeepAliveOk, $_.WriteFailed, $_.Marker }) + '| Run | Passed | Client path | Leak | Keep-alives OK | Slow ticks | Write failed | Marker |', '|---|---|---|---|---|---|---|---|' +) + ($rows | ForEach-Object { '| {0} | {1} | {2} | {3} | {4} | {5} | {6} | {7} |' -f $_.Run, $_.Passed, $_.ClientPath, $_.Leak, $_.KeepAliveOk, $_.SlowTicks, $_.WriteFailed, $_.Marker }) if ($env:GITHUB_STEP_SUMMARY) { $summary | Add-Content -Path $env:GITHUB_STEP_SUMMARY } $summary | Write-Host From db92bc838c551a52c6578c448d260038a497d1dc Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 20:13:13 +0000 Subject: [PATCH 4/5] TEMPORARY: issue #7 diagnostics with the fix on Counts late responses (send completed although cancelled) and runs the suite-context repro with the client fix enabled. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012kC9BM7EcqLbLxn8DocWHe --- .github/workflows/repro-issue7.yml | 2 +- src/Private/HttpClient.ps1 | 2 +- tools/repro/Invoke-Issue7Repro.ps1 | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/repro-issue7.yml b/.github/workflows/repro-issue7.yml index 4528460..8c54140 100644 --- a/.github/workflows/repro-issue7.yml +++ b/.github/workflows/repro-issue7.yml @@ -23,7 +23,7 @@ jobs: matrix: os: [windows-latest] pwsh: ['7.4.20', '7.5.11', '7.6.6'] - nofix: ['1'] + nofix: [''] steps: - name: Check out uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/src/Private/HttpClient.ps1 b/src/Private/HttpClient.ps1 index 308ceb1..408382e 100644 --- a/src/Private/HttpClient.ps1 +++ b/src/Private/HttpClient.ps1 @@ -604,7 +604,7 @@ function Invoke-McpHttpClientRequest { if (-not (Wait-McpTask -Task $sendTask -Deadline $deadline -OnTick $tick)) { Write-McpReproTrace "client id=$id header timeout; sendTask before Cancel: $($sendTask.Status)" Stop-McpHttpSendTask -Task $sendTask -Cts $cts - Write-McpReproTrace "client id=$id sendTask after Stop-McpHttpSendTask: $($sendTask.Status)$(if ($sendTask.Status -eq 'RanToCompletion') { ' -> late response DISPOSED (fix path)' })" + Write-McpReproTrace "client id=$id sendTask after Stop-McpHttpSendTask: $($sendTask.Status)$(if ($sendTask.Status -eq 'RanToCompletion') { if ($env:MCP_REPRO_NOFIX) { ' -> LATE RESPONSE LEAKED (fix off)' } else { ' -> LATE RESPONSE disposed (fix on)' } })" throw [System.TimeoutException]::new("No response headers from $($transport.Url) for '$Method' (id $id) within $TimeoutMs ms.") } $failure = Get-McpTaskFailure -Task $sendTask diff --git a/tools/repro/Invoke-Issue7Repro.ps1 b/tools/repro/Invoke-Issue7Repro.ps1 index f39e0a2..0a8ef96 100644 --- a/tools/repro/Invoke-Issue7Repro.ps1 +++ b/tools/repro/Invoke-Issue7Repro.ps1 @@ -33,7 +33,7 @@ if (`$r.PassedCount -ge 1 -and `$r.FailedCount -eq 0) { exit 0 } else { exit 1 } $output = & $pwsh -NoLogo -NoProfile -NonInteractive -Command $script 2>&1 $passed = $LASTEXITCODE -eq 0 $text = if (Test-Path $log) { Get-Content -Raw $log } else { '' } - $leak = $text -match 'LEAKED RESPONSE' + $leak = $text -match 'sendTask after Stop-McpHttpSendTask: RanToCompletion' $headerTimeout = $text -match 'header timeout' $sseTimeout = $text -match 'SSE read timeout' $writeFailed = $text -match 'SSE write FAILED' @@ -60,8 +60,8 @@ Remove-Item Env:MCP_REPRO_LOG $failed = @($rows | Where-Object { -not $_.Passed }).Count $summary = @( "## Issue #7 repro ($($Path -join ', '), whole files: $([bool] $WholeFiles)): $($PSVersionTable.OS), pwsh $($PSVersionTable.PSVersion)", '', - "Failures: **$failed / $Iterations**; leaked responses: $(@($rows | Where-Object Leak).Count)", '', - '| Run | Passed | Client path | Leak | Keep-alives OK | Slow ticks | Write failed | Marker |', '|---|---|---|---|---|---|---|---|' + "Failures: **$failed / $Iterations**; late responses (headers arrived during the cancel): $(@($rows | Where-Object Leak).Count)", '', + '| Run | Passed | Client path | Late response | Keep-alives OK | Slow ticks | Write failed | Marker |', '|---|---|---|---|---|---|---|---|' ) + ($rows | ForEach-Object { '| {0} | {1} | {2} | {3} | {4} | {5} | {6} | {7} |' -f $_.Run, $_.Passed, $_.ClientPath, $_.Leak, $_.KeepAliveOk, $_.SlowTicks, $_.WriteFailed, $_.Marker }) if ($env:GITHUB_STEP_SUMMARY) { $summary | Add-Content -Path $env:GITHUB_STEP_SUMMARY } $summary | Write-Host From c3138e908f387f5a7aceefa96f385a23d1235da1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 20:29:49 +0000 Subject: [PATCH 5/5] Remove the issue #7 diagnostics; document the timeout behaviour Drops the temporary trace points, the repro workflow and scripts, and the test-side TCP snapshots. The transport docs now state that a late response is disposed on timeout and that http.sys accepts one write after the client closed the connection; the changelog records the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012kC9BM7EcqLbLxn8DocWHe --- .github/workflows/repro-issue7.yml | 54 --------------------- CHANGELOG.md | 4 ++ docs/concepts/transports.md | 6 ++- src/Private/Dispatcher.ps1 | 2 - src/Private/HttpClient.ps1 | 5 -- src/Private/HttpServer.ps1 | 7 --- src/Private/ReproTrace.ps1 | 12 ----- tests/Integration/HttpServer.Tests.ps1 | 13 +---- tools/repro/Invoke-Issue7Repro.ps1 | 67 -------------------------- tools/repro/Invoke-Issue7Sweep.ps1 | 67 -------------------------- 10 files changed, 10 insertions(+), 227 deletions(-) delete mode 100644 .github/workflows/repro-issue7.yml delete mode 100644 src/Private/ReproTrace.ps1 delete mode 100644 tools/repro/Invoke-Issue7Repro.ps1 delete mode 100644 tools/repro/Invoke-Issue7Sweep.ps1 diff --git a/.github/workflows/repro-issue7.yml b/.github/workflows/repro-issue7.yml deleted file mode 100644 index 8c54140..0000000 --- a/.github/workflows/repro-issue7.yml +++ /dev/null @@ -1,54 +0,0 @@ -# TEMPORARY (issue #7): repeated runs of the flaky HTTP cancellation test; removed before the fix PR. -name: Repro issue 7 - -on: - push: - branches: [claude/vigilant-shannon-oubi04] - -permissions: - contents: read - -env: - POWERSHELL_TELEMETRY_OPTOUT: '1' - DOTNET_CLI_TELEMETRY_OPTOUT: '1' - DOTNET_NOLOGO: '1' - -jobs: - repro: - name: Repro (${{ matrix.os }}, pwsh ${{ matrix.pwsh }}, nofix=${{ matrix.nofix }}) - runs-on: ${{ matrix.os }} - timeout-minutes: 45 - strategy: - fail-fast: false - matrix: - os: [windows-latest] - pwsh: ['7.4.20', '7.5.11', '7.6.6'] - nofix: [''] - steps: - - name: Check out - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Install PowerShell ${{ matrix.pwsh }} - uses: ./.github/actions/install-pwsh - with: - version: ${{ matrix.pwsh }} - - name: Build - shell: pwsh - run: ./build.ps1 -Bootstrap -Task Build - - name: Whole HttpServer.Tests.ps1, 30 runs - shell: pwsh - env: - MCP_REPRO_NOFIX: ${{ matrix.nofix }} - run: ./tools/repro/Invoke-Issue7Repro.ps1 -Iterations 30 -WholeFiles - - name: Unit tests plus HttpServer.Tests.ps1, 8 runs - if: always() - shell: pwsh - env: - MCP_REPRO_NOFIX: ${{ matrix.nofix }} - run: ./tools/repro/Invoke-Issue7Repro.ps1 -Iterations 8 -WholeFiles -Path Unit, Integration/HttpServer.Tests.ps1 -LogDirectory output/repro/suite - - name: Upload traces - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: repro-${{ matrix.os }}-pwsh${{ matrix.pwsh }}-nofix${{ matrix.nofix }} - path: output/repro/ - if-no-files-found: warn diff --git a/CHANGELOG.md b/CHANGELOG.md index 5172745..59528f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -157,6 +157,10 @@ support, dependency and breaking-change policy. ### Fixed +- A Streamable HTTP request that timed out while its response headers were arriving left the response + undisposed, so its connection stayed open and the server never noticed that the client had given up; the + handler ran to completion. The client now disposes such a late response. The race was mostly hit on + Windows, where the HTTP cancellation test failed intermittently (#7). - A request id can be reused as soon as its response was sent; before, a request that arrived while the previous request with the same id was still winding down in its worker was rejected with `-32600`. - `Connect-McpServer -Server` fails at once for a server object that is already running, instead of waiting diff --git a/docs/concepts/transports.md b/docs/concepts/transports.md index d465d9c..f972496 100644 --- a/docs/concepts/transports.md +++ b/docs/concepts/transports.md @@ -66,7 +66,9 @@ runspace hosts it. Besides stdio there is an in-memory transport (a pair of chan `X-Accel-Buffering: no`); the response is the last event and closes the stream. A request that outlives `-KeepAliveSeconds` (default 5) also switches to SSE and receives keep-alive comments: a failed keep-alive write means the client closed the connection, which cancels the handler (token and pipeline stop). The - same happens when the final write fails. + same happens when the final write fails. On Windows, http.sys still accepts one write after the client + closed the connection and fails the next, so a closed connection is noticed one keep-alive interval later + than with the managed listener on Linux and macOS. - Shutdown (`Stop-McpServer`): the listener stops accepting, running handlers get the grace period, open channels receive an error response (`-32603`, "shutting down") and are closed. @@ -82,6 +84,8 @@ runspace hosts it. Besides stdio there is an in-memory transport (a pair of chan by event (`data:` lines joined, comments ignored, `id`/`retry` kept for the resumption of legacy sessions) with notifications dispatched to the progress and log callbacks until the response with the request id arrives. A deadline cancels the request and disposes the response, which closes the stream: the cancellation signal of this transport. + This includes a response whose headers arrive while the send is being cancelled (the send then completes + anyway): an undisposed response would keep the connection open, so the server's writes would never fail. - `Get-McpTool` validates the `x-mcp-header` annotations of every tool (`Get-McpToolHeaderParameter`) and excludes invalid tools with a warning; `Invoke-McpTool` derives the `Mcp-Param-*` headers from the cached annotations and, after a `-32020` from the server, refreshes the list and retries once. diff --git a/src/Private/Dispatcher.ps1 b/src/Private/Dispatcher.ps1 index 6671d99..65cf4fd 100644 --- a/src/Private/Dispatcher.ps1 +++ b/src/Private/Dispatcher.ps1 @@ -360,7 +360,6 @@ function Stop-McpInFlightRequest { ) $Entry.Cancelled = $true - Write-McpReproTrace "server id=$($Entry.Id) Stop-McpInFlightRequest (Cts.Cancel + BeginStop)" try { $Entry.Cts.Cancel() } catch { Write-Debug 'Cancelling the request token failed.' } try { $null = $Entry.PowerShell.BeginStop($null, $null) } catch { Write-Debug 'Stopping the worker pipeline failed.' } } @@ -436,7 +435,6 @@ function Update-McpInFlightRequest { } continue } - Write-McpReproTrace "server id=$($entry.Id) worker finished: $invocationState (cancelled=$($entry.Cancelled), responded=$($entry.Responded))" # A worker enqueues its response before it completes: deliver whatever is queued while the entry exists. Send-McpOutboundQueue -State $State if ($invocationState -eq [System.Management.Automation.PSInvocationState]::Failed -and -not $entry.Cancelled -and -not $entry.Responded) { diff --git a/src/Private/HttpClient.ps1 b/src/Private/HttpClient.ps1 index 408382e..2549936 100644 --- a/src/Private/HttpClient.ps1 +++ b/src/Private/HttpClient.ps1 @@ -116,7 +116,6 @@ function Stop-McpHttpSendTask { ) try { $Cts.Cancel() } catch { Write-Debug 'Cancelling the send failed.' } - if ($env:MCP_REPRO_NOFIX) { return } # TEMPORARY (issue #7 baseline) if (-not $Task.IsCompleted) { try { $null = $Task.Wait($SettleMs) } catch [System.AggregateException] { Write-Debug 'The cancelled send ended with an error.' } } @@ -325,7 +324,6 @@ function Receive-McpSseResponse { while ($true) { $remaining = ($Deadline - [datetime]::UtcNow).TotalMilliseconds if ($remaining -le 0) { - Write-McpReproTrace "client id=$Id SSE read timeout; disposing the reader" $Cts.Cancel() throw [System.TimeoutException]::new("No response to '$Method' (id $Id) within the timeout; the response stream was closed, which cancels the request.") } @@ -602,9 +600,7 @@ function Invoke-McpHttpClientRequest { $tick = if ($Session.Era -eq 'Legacy') { { Invoke-McpLegacyInbox -Session $Session } } else { $null } $sendTask = $transport.Client.SendAsync($message, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cts.Token) if (-not (Wait-McpTask -Task $sendTask -Deadline $deadline -OnTick $tick)) { - Write-McpReproTrace "client id=$id header timeout; sendTask before Cancel: $($sendTask.Status)" Stop-McpHttpSendTask -Task $sendTask -Cts $cts - Write-McpReproTrace "client id=$id sendTask after Stop-McpHttpSendTask: $($sendTask.Status)$(if ($sendTask.Status -eq 'RanToCompletion') { if ($env:MCP_REPRO_NOFIX) { ' -> LATE RESPONSE LEAKED (fix off)' } else { ' -> LATE RESPONSE disposed (fix on)' } })" throw [System.TimeoutException]::new("No response headers from $($transport.Url) for '$Method' (id $id) within $TimeoutMs ms.") } $failure = Get-McpTaskFailure -Task $sendTask @@ -629,7 +625,6 @@ function Invoke-McpHttpClientRequest { $mediaType = $null if ($null -ne $response.Content -and $null -ne $response.Content.Headers.ContentType) { $mediaType = $response.Content.Headers.ContentType.MediaType } Write-Debug "<- HTTP $status $mediaType for $Method id=$id" - Write-McpReproTrace "client id=$id headers received: HTTP $status $mediaType ($([int] ($deadline - [datetime]::UtcNow).TotalMilliseconds) ms before deadline)" if ($mediaType -eq 'text/event-stream') { return Receive-McpSseResponse -Session $Session -Response $response -Id $id -Method $Method -Deadline $deadline -Cts $cts -ProgressToken $progressToken -OnProgress $OnProgress } diff --git a/src/Private/HttpServer.ps1 b/src/Private/HttpServer.ps1 index d4c6f22..639c74e 100644 --- a/src/Private/HttpServer.ps1 +++ b/src/Private/HttpServer.ps1 @@ -370,7 +370,6 @@ function Start-McpHttpSse { $Channel.Mode = 'Sse' $Channel.LastWrite = [datetime]::UtcNow $State.Transport.OpenChannels.Add($Channel) - Write-McpReproTrace "server id=$($Channel.RequestId) switched to SSE" Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message ("-> HTTP 200 text/event-stream id={0}" -f $Channel.RequestId) return $true } catch { @@ -400,10 +399,8 @@ function Write-McpSseChunk { $Channel.Stream.Write($bytes, 0, $bytes.Length) $Channel.Stream.Flush() $Channel.LastWrite = [datetime]::UtcNow - if ($Text.StartsWith(':')) { Write-McpReproTrace "server id=$($Channel.RequestId) keep-alive write OK" } return $true } catch { - Write-McpReproTrace "server id=$($Channel.RequestId) SSE write FAILED: $($_.Exception.GetType().FullName): $($_.Exception.Message)" Write-McpStderr -Level Debug -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Writing to an SSE stream failed (id=$($Channel.RequestId)): $($_.Exception.Message)" Close-McpHttpChannel -State $State -Channel $Channel -Abort return $false @@ -528,7 +525,6 @@ function Stop-McpHttpChannelRequest { $entry = $State.InFlight[$key] if ($entry.Cancelled -or $entry.Responded) { return } Write-McpStderr -Level Info -Threshold $State.LogLevel -Logger $State.Server.Name -Message "Request $($entry.Id) ($($entry.Label)): the client closed the connection; cancelling." - Write-McpReproTrace "server id=$($entry.Id) Stop-McpHttpChannelRequest -> cancelling" Stop-McpInFlightRequest -Entry $entry $entry.Responded = $true } @@ -940,10 +936,7 @@ function Invoke-McpHttpDispatcherLoop { $listener = $transport.Listener $acceptTask = $listener.GetContextAsync() $stopDeadline = $null - $reproTick = [System.Diagnostics.Stopwatch]::StartNew() while ($true) { - if ($reproTick.ElapsedMilliseconds -gt 400) { Write-McpReproTrace "server dispatcher tick took $($reproTick.ElapsedMilliseconds) ms (in flight: $($State.InFlight.Count), open channels: $($transport.OpenChannels.Count))" } - $reproTick.Restart() $handles = [System.Collections.Generic.List[System.Threading.WaitHandle]]::new() if (-not $transport.Stopped) { $handles.Add((Get-McpTaskWaitHandle -Task $acceptTask)) } $handles.Add($State.Signal) diff --git a/src/Private/ReproTrace.ps1 b/src/Private/ReproTrace.ps1 deleted file mode 100644 index 157c40e..0000000 --- a/src/Private/ReproTrace.ps1 +++ /dev/null @@ -1,12 +0,0 @@ -# TEMPORARY (issue #7 diagnostics): appends a timestamped line to $env:MCP_REPRO_LOG when it is set. -function Write-McpReproTrace { - [CmdletBinding()] - param([Parameter(Mandatory)][string] $Message) - - $path = $env:MCP_REPRO_LOG - if (-not $path) { return } - $line = '{0} [t{1}] {2}{3}' -f [datetime]::UtcNow.ToString('HH:mm:ss.fff', [System.Globalization.CultureInfo]::InvariantCulture), [System.Threading.Thread]::CurrentThread.ManagedThreadId, $Message, [Environment]::NewLine - for ($attempt = 0; $attempt -lt 5; $attempt++) { - try { [System.IO.File]::AppendAllText($path, $line); return } catch { [System.Threading.Thread]::Sleep(2) } - } -} diff --git a/tests/Integration/HttpServer.Tests.ps1 b/tests/Integration/HttpServer.Tests.ps1 index d335673..c0ad26b 100644 --- a/tests/Integration/HttpServer.Tests.ps1 +++ b/tests/Integration/HttpServer.Tests.ps1 @@ -105,18 +105,7 @@ Describe 'Connect-McpServer over Streamable HTTP' -Tag 'Integration' { { Invoke-McpTool -Name 'count' -Arguments @{ To = 200; DelayMs = 50; MarkerPath = $marker } -TimeoutSeconds 1 -Session $script:session } | Should -Throw -ExceptionType ([System.TimeoutException]) (Invoke-McpTool -Name 'echo' -Arguments @{ Text = 'alive' } -Session $script:session).Text | Should -Be 'alive' $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - # TEMPORARY (issue #7 diagnostics): TCP states of the loopback connections to the server port. - $nextSnapshot = 0 - while (-not (Test-Path -Path $marker) -and $stopwatch.Elapsed.TotalSeconds -lt 8) { - if ($env:MCP_REPRO_LOG -and $IsWindows -and $stopwatch.Elapsed.TotalSeconds -ge $nextSnapshot) { - $nextSnapshot += 1 - $port = $script:handle.Port - $rows = @(Get-NetTCPConnection -ErrorAction SilentlyContinue | Where-Object { $_.LocalPort -eq $port -or $_.RemotePort -eq $port } | ForEach-Object { '{0}:{1}->{2}:{3} {4} pid={5}' -f $_.LocalAddress, $_.LocalPort, $_.RemoteAddress, $_.RemotePort, $_.State, $_.OwningProcess }) - [System.IO.File]::AppendAllText($env:MCP_REPRO_LOG, ('{0} test tcp@{1:n1}s: {2}{3}' -f [datetime]::UtcNow.ToString('HH:mm:ss.fff'), $stopwatch.Elapsed.TotalSeconds, ($rows -join ' | '), [Environment]::NewLine)) - } - Start-Sleep -Milliseconds 100 - } - if ($env:MCP_REPRO_LOG) { [System.IO.File]::AppendAllText($env:MCP_REPRO_LOG, ('{0} test marker after {1:n1}s: {2}{3}' -f [datetime]::UtcNow.ToString('HH:mm:ss.fff'), $stopwatch.Elapsed.TotalSeconds, $(if (Test-Path $marker) { [System.IO.File]::ReadAllText($marker) } else { 'MISSING' }), [Environment]::NewLine)) } + while (-not (Test-Path -Path $marker) -and $stopwatch.Elapsed.TotalSeconds -lt 8) { Start-Sleep -Milliseconds 100 } Test-Path -Path $marker | Should -BeTrue $text = [System.IO.File]::ReadAllText($marker) $text | Should -Match '^stopped at (\d+) of 200$' diff --git a/tools/repro/Invoke-Issue7Repro.ps1 b/tools/repro/Invoke-Issue7Repro.ps1 deleted file mode 100644 index 0a8ef96..0000000 --- a/tools/repro/Invoke-Issue7Repro.ps1 +++ /dev/null @@ -1,67 +0,0 @@ -# TEMPORARY (issue #7): runs the flaky integration test N times in fresh processes and classifies each run from -# the trace written by the instrumented module ($env:MCP_REPRO_LOG). Requires a built module under output/. -[CmdletBinding()] -param( - [int] $Iterations = 30, - [string] $LogDirectory = (Join-Path $PSScriptRoot '..' '..' 'output' 'repro'), - [string] $FullName = '*stops the handler when the client closes the connection on timeout*', - # Test files relative to tests/; the default runs only the flaky test's file. - [string[]] $Path = @('Integration/HttpServer.Tests.ps1'), - [switch] $WholeFiles -) - -$ErrorActionPreference = 'Stop' -$null = New-Item -ItemType Directory -Path $LogDirectory -Force -$LogDirectory = (Resolve-Path $LogDirectory).Path -$testFiles = ($Path | ForEach-Object { "'" + (Resolve-Path (Join-Path $PSScriptRoot '..' '..' 'tests' $_)).Path + "'" }) -join ',' -$pwsh = (Get-Process -Id $PID).Path -$rows = [System.Collections.Generic.List[object]]::new() -for ($i = 1; $i -le $Iterations; $i++) { - $log = Join-Path $LogDirectory ('{0}-run-{1:d2}.log' -f $(if ($WholeFiles) { 'files' } else { 'single' }), $i) - $env:MCP_REPRO_LOG = $log - $script = @" -Import-Module Pester -MinimumVersion 6.2.0 -`$c = New-PesterConfiguration -`$c.Run.Path = @($testFiles) -`$c.Run.PassThru = `$true -if (-not `$$([bool] $WholeFiles)) { `$c.Filter.FullName = '$FullName' } -`$c.Output.Verbosity = 'Normal' -`$r = Invoke-Pester -Configuration `$c -`$r.Failed | ForEach-Object { 'FAILED TEST: ' + `$_.ExpandedPath } -if (`$r.PassedCount -ge 1 -and `$r.FailedCount -eq 0) { exit 0 } else { exit 1 } -"@ - $output = & $pwsh -NoLogo -NoProfile -NonInteractive -Command $script 2>&1 - $passed = $LASTEXITCODE -eq 0 - $text = if (Test-Path $log) { Get-Content -Raw $log } else { '' } - $leak = $text -match 'sendTask after Stop-McpHttpSendTask: RanToCompletion' - $headerTimeout = $text -match 'header timeout' - $sseTimeout = $text -match 'SSE read timeout' - $writeFailed = $text -match 'SSE write FAILED' - $keepAlives = ([regex]::Matches($text, 'keep-alive write OK')).Count - $slowTicks = ([regex]::Matches($text, 'dispatcher tick took')).Count - $marker = if ($text -match 'test marker after [^:]+: (.*)') { $Matches[1].Trim() } else { '?' } - $row = [pscustomobject]@{ - Run = $i; Passed = $passed; ClientPath = $(if ($headerTimeout) { 'header-timeout' } elseif ($sseTimeout) { 'sse-timeout' } else { '?' }) - Leak = $leak; KeepAliveOk = $keepAlives; SlowTicks = $slowTicks; WriteFailed = $writeFailed; Marker = $marker - } - $rows.Add($row) - $row | Format-Table -HideTableHeaders | Out-String | Write-Host - if (-not $passed) { - Write-Host "---- run $i FAILED; Pester output ----" - $output | Select-Object -Last 40 | ForEach-Object { Write-Host $_ } - Write-Host "---- run $i trace (timeout test window) ----" - $lines = $text -split "`r?`n" - $start = [array]::FindIndex($lines, [Predicate[string]] { param($l) $l -match 'header timeout|SSE read timeout' }) - if ($start -lt 0) { $start = 0 } - $lines[[math]::Max(0, $start - 5)..[math]::Min($lines.Count - 1, $start + 120)] | ForEach-Object { Write-Host $_ } - } -} -Remove-Item Env:MCP_REPRO_LOG -$failed = @($rows | Where-Object { -not $_.Passed }).Count -$summary = @( - "## Issue #7 repro ($($Path -join ', '), whole files: $([bool] $WholeFiles)): $($PSVersionTable.OS), pwsh $($PSVersionTable.PSVersion)", '', - "Failures: **$failed / $Iterations**; late responses (headers arrived during the cancel): $(@($rows | Where-Object Leak).Count)", '', - '| Run | Passed | Client path | Late response | Keep-alives OK | Slow ticks | Write failed | Marker |', '|---|---|---|---|---|---|---|---|' -) + ($rows | ForEach-Object { '| {0} | {1} | {2} | {3} | {4} | {5} | {6} | {7} |' -f $_.Run, $_.Passed, $_.ClientPath, $_.Leak, $_.KeepAliveOk, $_.SlowTicks, $_.WriteFailed, $_.Marker }) -if ($env:GITHUB_STEP_SUMMARY) { $summary | Add-Content -Path $env:GITHUB_STEP_SUMMARY } -$summary | Write-Host diff --git a/tools/repro/Invoke-Issue7Sweep.ps1 b/tools/repro/Invoke-Issue7Sweep.ps1 deleted file mode 100644 index 45c3755..0000000 --- a/tools/repro/Invoke-Issue7Sweep.ps1 +++ /dev/null @@ -1,67 +0,0 @@ -# TEMPORARY (issue #7): sweeps the client timeout across the server's switch to SSE (KeepAliveSeconds = 1) so -# that the response headers arrive around the client deadline, and checks after each call whether the server -# stopped the handler. Platform independent; requires a built module under output/. -[CmdletBinding()] -param( - [int] $FromMs = 950, - [int] $ToMs = 1300, - [int] $StepMs = 10, - [string] $LogPath = (Join-Path $PSScriptRoot '..' '..' 'output' 'repro' 'sweep.log') -) - -$ErrorActionPreference = 'Stop' -$root = Join-Path $PSScriptRoot '..' '..' -Import-Module (Join-Path $root 'tests' 'Support' 'McpTestSupport.psm1') -Force -Import-Module (Get-McpBuiltModuleManifest) -Force -$null = New-Item -ItemType Directory -Path (Split-Path $LogPath) -Force -$env:MCP_REPRO_LOG = $LogPath -$server = New-McpServer -Name 'sweep' -Version '1.0.0' -RequestTimeoutSeconds 30 -Register-McpTool -Name 'count' -Description 'Counts; a marker file records where it stopped.' -ScriptBlock { - param([int] $To = 3, [int] $DelayMs = 20, [string] $MarkerPath = '', $Context) - $i = 0 - try { - for ($i = 1; $i -le $To; $i++) { - if ($Context.CancellationToken.IsCancellationRequested) { return "cancelled at $i" } - Start-Sleep -Milliseconds $DelayMs - } - "counted to $To" - } finally { - if ($MarkerPath) { [System.IO.File]::WriteAllText($MarkerPath, "stopped at $i of $To") } - } -} -Server $server -$handle = Start-McpTestHttpServer -Server $server -Parameters @{ KeepAliveSeconds = 1 } -$session = Connect-McpServer -Url $handle.Url -$module = Get-Module -Name ModelContextProtocol -$rows = [System.Collections.Generic.List[object]]::new() -try { - for ($timeout = $FromMs; $timeout -le $ToMs; $timeout += $StepMs) { - $marker = Join-Path ([System.IO.Path]::GetTempPath()) ('mcp-sweep-' + [guid]::NewGuid().ToString('n') + '.txt') - $params = [ordered]@{ name = 'count'; arguments = [ordered]@{ To = 200; DelayMs = 50; MarkerPath = $marker } } - $outcome = 'no timeout' - try { - $null = & $module { param($s, $p, $t) Invoke-McpHttpClientRequest -Session $s -Method 'tools/call' -Params $p -TimeoutMs $t } $session $params $timeout - } catch [System.TimeoutException] { - $outcome = 'timeout' - } - $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - while (-not (Test-Path -Path $marker) -and $stopwatch.Elapsed.TotalSeconds -lt 8) { Start-Sleep -Milliseconds 50 } - $text = if (Test-Path $marker) { [System.IO.File]::ReadAllText($marker) } else { 'MISSING' } - $stopped = $text -match '^stopped at (\d+) of 200$' -and [int] $Matches[1] -lt 150 - $rows.Add([pscustomobject]@{ TimeoutMs = $timeout; Client = $outcome; StoppedAfterS = [math]::Round($stopwatch.Elapsed.TotalSeconds, 1); Marker = $text; Ok = $stopped }) - Remove-Item -Path $marker -ErrorAction SilentlyContinue - } -} finally { - Disconnect-McpServer -Session $session - Stop-McpTestHttpServer -Handle $handle - Remove-Item Env:MCP_REPRO_LOG -} -$trace = Get-Content -Raw $LogPath -$leaks = ([regex]::Matches($trace, 'LEAKED RESPONSE')).Count -$bad = @($rows | Where-Object { -not $_.Ok }).Count -$summary = @( - "## Issue #7 timeout sweep: $($PSVersionTable.OS), pwsh $($PSVersionTable.PSVersion)", '', - "Handler not stopped: **$bad / $($rows.Count)**; leaked responses in the trace: $leaks", '', - '| Timeout (ms) | Client | Marker after (s) | Marker | OK |', '|---|---|---|---|---|' -) + ($rows | ForEach-Object { '| {0} | {1} | {2} | {3} | {4} |' -f $_.TimeoutMs, $_.Client, $_.StoppedAfterS, $_.Marker, $_.Ok }) -if ($env:GITHUB_STEP_SUMMARY) { $summary | Add-Content -Path $env:GITHUB_STEP_SUMMARY } -$summary | Write-Host