Skip to content

Fix cancellation issues for dropped connections #633

Closed

Description

@oldsaltycrab

Hello, when reading up on how best to cancel a task with a timeout, Stephen Cleary suggests in his book (http://stephencleary.com/book/) that the CancellationTokenSource with a TimeSpan set is more efficient than doing await Task.WhenAny(SomeMethodAsync(), Task.Delay(timeout));. It also propagates the exception nicely.

In Npgsql the CancellationToken only makes it to ExecuteDbDataReaderAsync, so unless cancellation has been requested by that point, it won't work.

I've seen other libraries implement this with fairly low impact using optional arguments, eg: public FooAsync(CancellationToken cancellationToken = default(CancellationToken))

I haven't done any benchmarks so I don't know the impact of one over the other exactly so I'm fine to use the Task.WhenAny method described in #631 for the time being.

Thanks

Activity

  1. roji commented on Jun 5, 2015

    @roji
    Member

    @oldsaltycrab, I'm not near my computer to test but I think what you describe should already work.

    The three async execute methods register a callback on the cancellation token before they start actually doing their work. This means that the moment the cancellation token is triggered (via a timeout or any other mechanism), the command's Cancel() method is called as usual as if the user called it directly. Is this behavior not working for you?

    However, note that there's a subtle but important difference between this technique and awaiting on a Task.Delay() for timeouts... Triggering a cancellation token does nothing but indicate that a task should be cancelled - it doesn't force cancellation. For example, if a connection is silently dropped somehow, calling cancel won't do anything at all, since it simply connects to the backend and politely asks it to cancel the ongoing operation. On the other hand, the technique with Task.Delay() implements the timeout client-side and will always work.

    There's an analogy to be made between these two techniques and Npgsql's backend vs. frontend timeout. Backend timeouts and command cancellations are great because they inform the backend of the cancellation, and therefore after a cancellation the connection can be reused. Frontend timeouts (socket- or timer-based), on the other hand, will always work, but since they don't coordinate anything with the backend they leave your connection in an unusable state. So frontend timeouts should be used as a fallback in case backend timeouts fail (e.g. half-open connection).

    Let me know if something isn't working etc.

  2. oldsaltycrab commented on Jun 5, 2015

    @oldsaltycrab
    Author

    @roji, from what I understand, the token itself must be checked if cancellation has been requested in order to trigger the cancellation exception. So yes, like you said, it's not forced simply by setting IsCancellationRequested to true. I went with the assumption that the underlying objects that Npgsql uses (mainly streams in this case) would be checking for the cancellation and it looks like that is the case.

    The easiest way for me to reproduce a dropped connection (on the server) is still by using the method I described in #630. When I do that, using a short timespan in the CancellationToken and the current implementation, it won't trigger anything. I can even play with it by stepping through and seeing IsCancellationRequested set to true, but if it's after your initial check then nothing will happen.

    I experimented yesterday with implementing CancellationTokens throughout the Npgsql async methods (not that I would want to create a PR, as to do it I just temporarily disabled AsyncRewriter) and if the Task exceeds its timeout, a TaskCanceledException will be thrown inside the Underlying.ReadAsync method inside EnsureAsync. In this case I didn't add any checks, just passed the token right on through into the underlying methods. That being said, my understanding of this topic is far from complete so please test it out when you get a chance.

    I also have a question about your Task.Delay() technique. I went to implement this yesterday but couldn't figure out a way to kill the timed out task. If the Delay task is the first to come out of the Task.WhenAny operation, what steps do you take to actually "timeout" the other task? My understanding is that unless you do some work directly with the ThreadPool, you can't cancel a Task in a safe manner without using a CancellationToken. If you simply throw an exception or have some other kind of error logged upon the Delay task finishing then the initial Task that you were waiting on (and is now hanging) is still out there attempting to finish?

    Let me know your thoughts on that.

  3. changed the title [-]Propagate cancellationtokens through async methods[/-] [+]Fix cancellation issues for dropped connections[/+] on Jun 7, 2015
  4. added this to the milestone on Jun 7, 2015
  5. roji commented on Jun 7, 2015

    @roji
    Member

    @oldsaltycrab,

    From my understanding, there's nothing special about the cancellation exception - it's just a TaskCanceledException. Calling IsCancellationRequested when the token has already been cancelled is one way to produce and throw this exception, but is seems OK to register a call and then to "manually" instantiate and throw it, just the Npgsql code currently does.

    However, on the more general issue you're right: since the async flow doesn't pass the cancellation token all the way down the stack, cancellation support is currently flawed - thanks for drawing my attention to that. Cases where cancellation currently fails are:

    • A half-open (i.e. dropped) connection scenario like the one you created. Since the token doesn't make it to down to the stream, no frontend timeout mechanism is at work and we're stuck forever.
    • If cancellation is requested after the IsCancellationRequested check, but before the query actually starts at the backend. This is a rare and subtle race condition, but still important.

    Note that for normal operations, where the connection is fine and an operation is in progress, cancellation should definitely work fine (this is the "backend", rather than "frontend" cancellation): the callback triggers the PostgreSQL cancel, which returns the correct NpgsqlException.

    However, there's an even more subtle problem here... if a cancellation is requested under normal conditions (i.e. the connection is fine and an operation is in progress), we don't want the the network stream cancellation to be triggered. The reason for this is that a stream cancellation would leave the connection in an unusable state (much like a frontend timeout) - we've lost sync with the server. The correct solution here seems to be to first request a backend cancellation (via the regular NpgsqlCommand.Cancel), and if that hasn't taken effect within X seconds, trigger a "frontend" cancellation and set the connection to state broken.

    Note also that this same bug happens with synchronous cancellations: if you try to call cancel on a dropped connection (or, for that matter, before the backend operation has started), you'll remain stuck forever.

    Because of behavior complexity and the probable work needed on the async rewriter, I think it's too late to do this for 3.0, but it should definitely be a goal for 3.1. I'll document this in the 3.0 release notes and am

    Thanks again for studying this in detail and making all the helpful comments!

  6. roji commented on Apr 20, 2016

    @roji
    Member

    Looking at this again, the current state of things in the develop branch seems... confusing. Since we last discussed this, in Npgsql's develop branch we pass cancellation tokens all the way down. So now there are two things that happen when you trigger a cancellation via a cancellation token:

    • An Npgsql-registered callback is invoked, calling Cancel on the command. This opens a separate connection to the backend, and sends a cancellation request. This is backend cancellation.
    • The token itself is passed down all the way to the I/O functions (e.g. NetworkStream.ReadAsync). This means that any pending write or read operation is cancelled immediately. This is new in dev, Npgsql 3.0 didn't pass the cancellation token down. This is frontend cancellation.

    First off, this means that the cancel callback is pretty much useless... Whatever I/O operation is currently in progress (or which will start soon) will be immediately cancelled, not giving the backend cancellation path a chance to do its job.

    What exactly should we do here? Pros and cons of each cancellation method:

    • Backend cancellation has the disadvantages outlined in this issue - it doesn't always work. If there's a network connectivity issue, if the original connection is half-open, or if you hit the cancel button too early - your request is silently ignored and you're stuck. Even in the best of conditions, the cancellation isn't very punctual: you have to deliver the cancellation to the server and then read the remaining results - this takes time.
    • Frontend cancellation always works, is always immediate, but (like frontend timeouts) it leaves the connection in a broken state, because we've lost sync with the server.

    Options going forward:

    • Leave the choice up the user, by saying that the cancellation token is a frontend-only mechanism, while NpgsqlCommand.Cancel() is the backend mechanism.
    • Make the cancellation token (and maybe also NpgsqlCommand.Cancel()) do both things: first attempt to do a backend cancellation, and after some fixed amount of time, do a frontend cancellation. This isn't immediate, but at least will always work (after a while), and is somewhat complicated to implement.
    • Keep frontend cancellation, but make sure that when the connection is broken we implicitly open another one. This provides a nice experience to the user, but the connection state is lost (parameters, transaction...), and hides an expensive operation under the hood. Note that SqlClient does recover after cancellations (and timeouts), although I have no idea how this is implemented.

    Any comments from anyone?

  7. roji commented on Apr 24, 2016

    @roji
    Member

    A very important fact I just came across (and don't believe I wasn't aware of), is that .NET NetworkStream doesn't respect cancellation tokens. We would have to hack around this by registering a callback that closes the socket (see https://social.msdn.microsoft.com/Forums/en-US/54632b19-0e9c-4078-aa59-c4389e75b187/mixing-legacy-apm-with-asyncctp?forum=async). This doesn't fundamentally change anything, only the callback that gets called when cancelling (i.e. it's irrelevant whether we pass the token down or not).

  8. roji commented on May 1, 2016

    @roji
    Member

    Deferring this to 3.2 as it's not immediately clear what to do: retain the current behavior (have the cancellation token trigger backend cancellation) or switch to closing the socket, which would immediately cancel the operation and break the connection.

  9. modified the milestones: 3.2, on May 1, 2016
  10. xanather commented on Jun 21, 2016

    @xanather

    @roji Hopefully Microsoft will get around to it https://github.com/dotnet/corefx/issues/5211
    This was also a blocker for me with WaitAsync (makes cleanup difficult).

  11. roji commented on Jun 21, 2016

    @roji
    Member

    @xanather thanks for linking to the issue, I'll try to track progress...

  12. removed this from the 3.2 milestone on Sep 25, 2016
  13. added this to the Backlog milestone on Jun 8, 2018
  14. vonzshik commented on Jan 1, 2021

    @vonzshik
    Contributor

    Closing this issue, as with 5.0 cancellation was fully redone and the token is finally passed to the stream.

  15. added theissue type on Jun 18, 2025
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

    No labels
    No labels

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions