Skip to content

Exception caused by a race condition when KeepAlive is enabled #1151

Closed

Description

@MarkusSintonen

Hi!

We have encountered a possible bug with KeepAlive feature in Npgsql 3.1.3. We have an application that uses few long living connections to a database with keep alive enabled (10 seconds). These connections are disposed normally when no longer used after a while. However the keep alive feature has caused randomly happening crashes of the application. Here is the stack trace of the crash:

System.ObjectDisposedException: The semaphore has been disposed.
   at System.Threading.SemaphoreSlim.CheckDispose()
   at System.Threading.SemaphoreSlim.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.PerformKeepAlive(Object state)
   at System.Threading.TimerQueueTimer.CallCallbackInContext(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.TimerQueueTimer.CallCallback()
   at System.Threading.TimerQueueTimer.Fire()
   at System.Threading.TimerQueue.FireQueuedTimerCompletion(Object state)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

There seems to be a race condition bug with keep alive and disposing of the connection. When looking at the source code of the NpgsqlConnector.PerformKeepAlive it is clear that the _keepAliveLock semaphore has been disposed at the start of timer thread by another thread (by calling the Dispose on the NpgsqlConnection). Although the NpgsqlConnector.Cleanup method stops the keep alive timer before disposing the _keepAliveLock semaphore, this doesn't take into account if the timer thread is already currently running. Instead the NpgsqlConnector.Cleanup should wait for the possibly running keep alive thread and then dispose the semaphore after the keep alive is ready.

This is quite a critical bug since this possibly causes full crash of the application when keep alive feuture is used.

BR
Markus Sintonen

Activity

  1. self-assigned this
    on Jun 8, 2016
  2. roji commented on Jun 8, 2016

    @roji
    Member

    Thanks for the bug and for the correct analysis, this is just in time two (I'm about to release 3.1.4).

    This is ultimately caused by #1127 - closing a connection does not currently acquire any locks, and therefore can cause a race condition with keepalives happening at the same time. However, #1127 is linked to some other work I want to do for 3.2 so for 3.1 we need another solution.

    Regarding your fix, I'm not sure how Cleanup would wait for the keepalive thread to complete with... some synchronization mechanism such as a semaphore :) I'd also prefer not blocking Cleanup in general. A much easier solution would simply be to catch the exception coming out of the Wait() method and silently ignore it.

  3. roji commented on Jun 8, 2016

    @roji
    Member

    Hmm, that fix would probably solve this, but there's still a race condition as the keepalive code actually tries to write to the socket... will look deeper into this.

  4. reopened this on Jun 8, 2016
  5. roji commented on Jun 8, 2016

    @roji
    Member

    There's probably no way to actually solve this without doing #1127 in one way or another,.

  6. MarkusSintonen commented on Jun 9, 2016

    @MarkusSintonen
    ContributorAuthor

    Yeah I think this needs some rethinking of synchronization between keep alives and user actions. After the commit 4bc1550, there still exists a second ObjectDisposedException caused by a race condition.

    Consider the following:
    First thread: user disposes the connection normally and NpgsqlConnector.Cleanup() disposes all the resources e.g. the _keepAliveLock.
    Second timer thread (PerformKeepAlive): is currently inside the block that throws ObjectDisposedException with _keepAliveLock.Release() inside try-catch block since the first thread already disposed this. This exception is handled but NpgsqlConnector.Break() is called which in turn calls NpgsqlConnector.Cleanup(). Here we again get the ObjectDisposedException since the connection has been already disposed by another thread. This exception is not handled anywhere and we get unhandled exception inside the timer thread.

    Is this analysis correct?

  7. roji commented on Jun 9, 2016

    @roji
    Member

    I agree, there's no way around properly taking locks for the connection close operation. This would probably fix some other undiscovered concurrency bugs which are in there. The thing that makes it a bit complicated is that Close() is supposed to work even if a user operation is already currently in progress (i.e. "violent" shutdown).

    I'll work on this in the coming days and release a fix in 3.1.4. I'm off for several months on a very intensive project starting next week, so I'd really like to get this out ASAP. If you can be on standby to quickly test my fix for this that would be great.

  8. MarkusSintonen commented on Jun 9, 2016

    @MarkusSintonen
    ContributorAuthor

    Yes I can test and check the code.
    Should there be some intensive and long running test for the Npgsql so these kind of errors would be noticed?

  9. roji commented on Jun 9, 2016

    @roji
    Member

    @MarkusSintonen there probably should, although concurrency tests are a very difficult thing to get just right. I'd definitely accept a PR with concurrency tests.

  10. roji commented on Jun 13, 2016

    @roji
    Member

    @MarkusSintonen, I dived into properly fixing things and found other related problems with Close: in the current implementation it won't always succeed (e.g. losing network connectivity). Also, if an operation is already in progress (NpgsqlDataReader, COPY) it will nicely close it, which may mean waiting for a long time. This makes no sense to me - a close should be immediate.

    Unfortunately fixing all this requires a real redo of Close, which is too much for a 3.1.x patch release. This should definitely happen for 3.2, but for now I'd like to try a dirty workaround as originally suggested. I took into account your correct analysis in #1151 (comment) and added more try/catches in PerformKeepAlive, please take a look at the code (branch keepalive-workaround). You can also install the version with the workaround from the stable feed, it's called #3.1.4-ci-244.

    Since I'd like to release 3.1.4 ASAP, I'd really appreciate it if you could test-drive this package and let me know if it works well.

  11. 2 remaining items

  12. roji commented on Jun 14, 2016

    @roji
    Member

    Great. I agree this is a temporary workaround and nothing more, 3.2 will include a more proper redo. I'll release 3.1.4 ASAP.

  13. added this to the 3.1.4 milestone on Jun 14, 2016
  14. added a commit that references this issue on Jun 14, 2016
    da45c15
  15. modified the milestones: 3.0.8, 3.1.4 on Jun 14, 2016
  16. roji commented on Jun 14, 2016

    @roji
    Member

    Fixed in 3.0.8, 3.1.4

  17. added 2 commits that reference this issue on Jun 14, 2016
    39f9b0a
    cfe886f
  18. 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

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions