Skip to content

Cancelling Http requests can result in "The handle is invalid" or other WinHTTP state errors #17542

Closed

Description

@davidsh

Http requests can be cancelled in various ways using a cancellation token or even a timeout. Sometimes the CI tests timeout contacting the Azure test server due to network congestion, so this results in the requests getting cancelled as well by the HttpClient.Timeout property.

When Http requests are cancelled in WinHttpHandler, the WinHTTP handle is closed. This cancels any outstanding async operations in WinHTTP. However, the current CancellationTokenRegistration code is closing the handle without first seeing if there is an active operation in flight.

private async void StartRequest(object obj)
{

    // ...
    using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))                
    {
        do
        {
            // ...
        } while (state.RetryRequest);
    }

Since this cancellation is happening on a different thread from the main StartRequest() logic, it results in in-deterministic behavior.

PR dotnet/corefx#8693 (Fix cancellation of WinHttpHandler response stream reads) has a similar CancellationToken.Register logic but it correctly checks for an active operation. This same logic needs to apply to the StartRequest() operation.

This is the root cause of the following issues:
#17434
#17271
#17244
#17112
#17089

History of failures

System.Net.Http.HttpRequestException : An error occurred while sending the request.
---- System.Net.Http.WinHttpException : The handle is invalid
Day Build OS Test
5/9 20170509.01 Win7 Timeout_SetTo30AndGetResponseFromLoopbackQuickly_Success
5/10 20170510.01 Win7 GetAsync_AllowedSSLVersion_Succeeds
5/11 20170511.01 Win7 GetAsync_AllowedSSLVersion_Succeeds
5/19 20170519.04 Win7 PostAsync_CallMethod_StreamContent
5/26 20170526.01 Win7 PostLongerContentLengths_UsesChunkedSemantics
5/30 20170530.06 Win7 SetDelegate_ConnectionSucceeds
6/4 20170604.02 Win7 NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds
6/7 20170607.01 Win7 PostSyncBlockingContentUsingChunkedEncoding_Success
6/13 20170613.02 Win7 SetDelegate_ConnectionSucceeds
6/14 20170614.01 Win7 PostAsync_CallMethod_StreamContent
6/15 20170615.03 Win7 NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds
6/15 20170615.03 Win8.1 GetAsync_ServerNeedsNonStandardAuthAndSetCredential_StatusCodeUnauthorized
6/16 20170616.01 Win7 PostAsync_CallMethod_EmptyContent
9/26 20170926.06 Win7 ReadAsStreamAsync_ValidServerResponse_Success
10/10 20171010.03 Win7 GetStreamAsync_ReadToEnd_Success
10/11 20171011.02 Win7 PostAsync_CallMethod_StreamContent
10/20 20171020.01 Win7 SetDelegate_ConnectionSucceeds
10/22 20171022.01 Win7 MaxResponseContentBufferSize_ThrowsIfTooSmallForContent
10/22 20171022.02 Win7 MaxResponseContentBufferSize_ThrowsIfTooSmallForContent
10/23 20171023.02 Win7 ReadAsStreamAsync_ValidServerResponse_Success
10/25 20171025.04 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
10/25 20171025.08 Win7 PostRewindableContentUsingAuth_NoPreAuthenticate_Success
10/25 20171025.08 Win7 PostAsync_CallMethod_StreamContent
10/27 20171027.03 Win7 PostUsingContentLengthSemantics_Success
10/30 20171030.01 Win7 PostRewindableContentUsingAuth_NoPreAuthenticate_Success
10/30 20171030.02 Win7 GetAsync_SupportedSSLVersion_Succeeds
10/31 20171030.05 Win7 SetDelegate_ConnectionSucceeds
11/3 20171103.07 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
11/6 20171106.03 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
11/6 20171106.01 Win7 PostRewindableContentUsingAuth_NoPreAuthenticate_Success
11/7 20171107.02 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
11/9 20171109.04 Win7 ReadAsStreamAsync_ValidServerResponse_Success
11/15 20171115.02 Win7 PostAsync_EmptyContent_ContentTypeHeaderNotSent
11/15 20171115.03 Win7 GetAsync_TrailingHeaders_Ignored
11/18 20171118.04 Win7 GetStreamAsync_ReadZeroBytes_Success
11/20 20171120.01 Win7 GetAsync_TrailingHeaders_Ignored
11/20 20171120.02 Win7 GetAsync_AllowedSSLVersion_Succeeds
11/22 20171122.02 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
11/23 20171123.02 Win7 GetAsync_ServerNeedsNonStandardAuthAndSetCredential_StatusCodeUnauthorized
11/24 20171124.01 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
11/27 20171127.06 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
11/28 20171128.01 Win7 SetDelegate_ConnectionSucceeds
11/28 20171128.07 Win10 UseCallback_NotSecureConnection_CallbackNotCalled
12/5 20171205.05 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
12/5 20171205.06 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
12/8 20171208.01 Win7 PostAsync_EmptyContent_ContentTypeHeaderNotSent
12/12 20171212.02 Win7 GetStreamAsync_ReadToEnd_Success
12/23 20171223.01 Win7 GetAsync_MaxLimited_ConcurrentCallsStillSucceed - link
12/24 20171224.02 Win7 GetAsync_MaxLimited_ConcurrentCallsStillSucceed - link
12/31 20171231.01 Win7 GetAsync_ServerNeedsNonStandardAuthAndSetCredential_StatusCodeUnauthorized - link
1/5 20180105.01 Win7 SetDelegate_ConnectionSucceeds - link
1/10 20180110.03 Win7 GetAsync_ExpectedStatusCodeAndReason_Success - link
1/11 20180111.02 Win7 GetAsync_ExpectedStatusCodeAndReason_Success - link
1/14 20180114.01 Win7 PostAsync_EmptyContent_ContentTypeHeaderNotSent - link
1/16 20180116.01 Win7 SetDelegate_ConnectionSucceeds - link
1/18 20180118.04 Win7 MaxResponseContentBufferSize_ThrowsIfTooSmallForContent - link
1/19 20180119.02 Win7 GetAsync_AllowedSSLVersion_Succeeds - link
1/19 20180119.04 Win7 PostUsingContentLengthSemantics_Success - link
1/21 20180121.01 Win7 MaxResponseContentBufferSize_ThrowsIfTooSmallForContent - link
1/22 20180122.02 Win7 ReadAsStreamAsync_ValidServerResponse_Success - only in catastrophic failure logs
1/23 20180123.01 Win7 PostRewindableContentUsingAuth_NoPreAuthenticate_Success - link
1/23 20180123.01 Win7 GetAsync_ExpectedStatusCodeAndReason_Success - link
1/23 20180123.01 Win7 GetAsync_MaxLimited_ConcurrentCallsStillSucceed - link
1/25 20180125.01 Win7 PostAsync_ReuseRequestContent_Success - link
1/27 20180127.01 Win7 GetAsync_TrailingHeaders_Ignored - link
1/27 20180127.04 Win10 PostRepeatedFlushContentUsingChunkedEncoding_Success - link
1/27 20180127.04 Win7 GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri - only in catastrophic failure logs
1/29 20180129.05 Win7 GetAsync_MaxLimited_ConcurrentCallsStillSucceed - link
1/30 20180130.05 Win7 PostEmptyContentUsingConflictingSemantics_Success - only in catastrophic failure logs
1/31 20180131.05 Win7 SetDelegate_ConnectionSucceeds - link
2/1 20180201.01 Win7 PostUsingChunkedEncoding_Success - link
2/1 20180201.01 Win7 GetAsync_MaxLimited_ConcurrentCallsStillSucceed - link
2/1 20180201.05 Win7 GetAsync_ExpectedStatusCodeAndReason_Success - link
2/5 20180205.01 Win7 SetDelegate_ConnectionSucceeds - link
2/6 20180206.04 Win7 SetDelegate_ConnectionSucceeds - link
2/6 20180206.05 Win7 UseCallback_NotSecureConnection_CallbackNotCalled - link
2/8 20180208.01 Win7 2x GetAsync_ExpectedStatusCodeAndReason_Success - link and link
2/9 20180209.05 Win7 ThresholdExceeded_ThrowsException - link
2/10 20180210.01 Win7 GetAsync_MaxLimited_ConcurrentCallsStillSucceed - link
2/10 20180210.01 Win7 GetAsync_ExpectedStatusCodeAndReason_Success - only in catastrophic failure logs
2/13 20180213.01 Win7 ThresholdExceeded_ThrowsException
2/20 20180220.08 Win7 The handle is invalid
2/21 20180221.01 Win7 The handle is invalid
2/25 20180225.01 Win7 HttpClientHandler_IncorrectCredentials_Fails - link
2/25 20180225.02 Win10 HttpClientHandler_Authentication_Succeeds - link
2/26 20180226.04 Win7 GetAsync_AllowedSSLVersion_Succeeds - link
2/28 20180228.07 Win7 ThresholdExceeded_ThrowsException
3/1 20180301.01 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
3/2 20180302.06 Win7 ReadAsStreamAsync_ValidServerResponse_Success
3/4 20180304.01 Win7 ReadAsStreamAsync_ValidServerResponse_Success
3/7 20180307.03 Win7 GetAsync_MaxLimited_ConcurrentCallsStillSucceed
3/7 20180307.03 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
3/7 20180307.04 Win7 ReadAsStreamAsync_ValidServerResponse_Success
3/8 20180308.01 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
3/8 20180308.09 Win7 GetAsync_SetCookieContainer_CookieSent
3/10 20180310.02 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
3/14 20180314.01 Win7 GetAsync_ExpectedStatusCodeAndReason_Success
3/17 20180317.03 Win7 GetAsync_MaxLimited_ConcurrentCallsStillSucceed
3/22 20180322.06 Win7 ThresholdExceeded_ThrowsException

Similar failure with IOException wrapped in the middle

System.Net.Http.HttpRequestException   : Error while copying content to a stream.
---- System.IO.IOException :   The write operation failed, see inner exception.
--------   System.Net.Http.WinHttpException : The handle is invalid
Day Build OS Test
11/17 20171117.04 Win7 PostUsingContentLengthSemantics_Success
12/2 20171202.01 Win7 PostAsync_ReuseRequestContent_Success

Activity

  1. self-assigned this
    on Jun 7, 2016
  2. davidsh commented on Jun 7, 2016

    @davidsh
    ContributorAuthor
  3. karelz commented on Feb 23, 2017

    @karelz
    Member

    This is tricky poitned fix - @davidsh has background.
    Contributes to scenario in #17392.

  4. krwq commented on Apr 17, 2017

    @krwq
    Member

    What's the status on this? Has anyone had a chance to look at this?

  5. karelz commented on Apr 18, 2017

    @karelz
    Member

    @krwq judging from the fact it is unassigned and opened, I don't think anyone looked into it yet ...

  6. danmoseley commented on Apr 26, 2017

    @danmoseley
    Contributor

    Not a regression from Desktop nor 1.0

  7. davidsh commented on Apr 26, 2017

    @davidsh
    ContributorAuthor

    Not a regression from Desktop nor 1.0

    Strictly speaking, it is a regression from Desktop in the reliability sense. But Desktop has a completely different implementation (doesn't use 'handles').

  8. changed the title [-]Cancelling Http requests can result in "The handle is invalid" errors[/-] [+]Cancelling Http requests can result in "The handle is invalid" or other WinHTTP state errors[/+] on May 9, 2017
  9. KristinXie1 commented on Sep 6, 2017

    @KristinXie1

    Failed again in UWP ILC tests, detail: https://mc.dot.net/#/product/netcore/master/source/official~2Fcorefx~2Fmaster~2F/type/test~2Ffunctional~2Filc~2F/build/20170906.01/workItem/System.Net.Http.Functional.Tests

    Message:
    System.Net.Http.HttpRequestException : An error occurred while sending the request.
    ---- System.Exception : Operation aborted (Exception from HRESULT: 0x80004004)

  10. KristinXie1 commented on Sep 19, 2017

    @KristinXie1
  11. stephentoub commented on Nov 20, 2017

    @stephentoub
    Member

    Failed again here:
    https://ci3.dot.net/job/dotnet_corefx/job/master/job/windows-TGroup_netcoreapp+CGroup_Release+AGroup_x64+TestOuter_true_prtest/8/

    Message :
    System.Net.Http.HttpRequestException : An error occurred while sending the request.
    ---- System.Net.Http.WinHttpException : The handle is invalid
    Stack Trace :
       at System.Net.Http.HttpClient.<FinishSendAsyncBuffered>d__58.MoveNext() in D:\j\workspace\windows-TGrou---6368dffa\src\System.Net.Http\src\System\Net\Http\HttpClient.cs:line 464
    --- End of stack trace from previous location where exception was thrown ---
       at System.Net.Http.Functional.Tests.PostScenarioTest.<PostUsingAuthHelper>d__25.MoveNext() in D:\j\workspace\windows-TGrou---6368dffa\src\System.Net.Http\tests\FunctionalTests\PostScenarioTest.cs:line 239
    --- End of stack trace from previous location where exception was thrown ---
       at System.Net.Http.Functional.Tests.PostScenarioTest.<PostRewindableContentUsingAuth_NoPreAuthenticate_Success>d__20.MoveNext() in D:\j\workspace\windows-TGrou---6368dffa\src\System.Net.Http\tests\FunctionalTests\PostScenarioTest.cs:line 148
    --- End of stack trace from previous location where exception was thrown ---
    --- End of stack trace from previous location where exception was thrown ---
    --- End of stack trace from previous location where exception was thrown ---
    ----- Inner Stack Trace -----
       at System.Net.Http.WinHttpException.ThrowExceptionUsingLastError() in D:\j\workspace\windows-TGrou---6368dffa\src\Common\src\System\Net\Http\WinHttpException.cs:line 44
       at System.Net.Http.WinHttpHandler.SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle) in D:\j\workspace\windows-TGrou---6368dffa\src\System.Net.Http.WinHttpHandler\src\System\Net\Http\WinHttpHandler.cs:line 1082
       at System.Net.Http.WinHttpHandler.SetRequestHandleOptions(WinHttpRequestState state) in D:\j\workspace\windows-TGrou---6368dffa\src\System.Net.Http.WinHttpHandler\src\System\Net\Http\WinHttpHandler.cs:line 956
       at System.Net.Http.WinHttpHandler.<StartRequest>d__105.MoveNext() in D:\j\workspace\windows-TGrou---6368dffa\src\System.Net.Http.WinHttpHandler\src\System\Net\Http\WinHttpHandler.cs:line 833
    
  12. karelz commented on Dec 14, 2017

    @karelz
    Member

    I added history of the failures to the top post - it's about 15 per month in official builds (excluding PRs which show 5 failures since October).

  13. karelz commented on Jan 17, 2018

    @karelz
    Member

    Triage: No customer complaints yet. We would like to fix it to propagate proper exception, but may not fit into 2.1 - moving to Future.

  14. davidsh commented on Sep 4, 2019

    @davidsh
    ContributorAuthor

    Closing due to age of issue.

  15. transferred this issue fromdotnet/corefxon Jan 31, 2020
  16. added this to the 5.0 milestone on Jan 31, 2020
  17. ghost locked as resolved and limited conversation to collaborators on Dec 31, 2020
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

    area-System.Net.Httpbugos-windowstenet-reliability

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions