Skip to content

Command never gets garbage allocated if not disposed #505

Closed

Description

@havard

I have a scenario where a process runs in Azure for a long time, querying a database rather eagerly. I estimate the load to be 5-20 queries/second.

The issue

After running for about 4 hours, the job consistently fails to connect to the database. The relevant exception and stack trace is given below:

An exception of type Npgsql.NpgsqlException was thrown: Failed to establish a connection to 'database-host'. 
Stack trace: 
  at Npgsql.NpgsqlClosedState.Open(NpgsqlConnector context, Int32 timeout)
  at Npgsql.NpgsqlConnector.Open()
  at Npgsql.NpgsqlConnectorPool.GetPooledConnector(NpgsqlConnection Connection) 
  at Npgsql.NpgsqlConnectorPool.RequestPooledConnectorInternal(NpgsqlConnection Connection) 
  at Npgsql.NpgsqlConnectorPool.RequestConnector(NpgsqlConnection Connection) 
  at Npgsql.NpgsqlConnection.Open() at System.Data.Common.DbConnection.OpenAsync(CancellationToken cancellationToken) 
  --- End of stack trace from previous location where exception was thrown --- 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
  at System.Data.Entity.Core.EntityClient.EntityConnection.d__8.MoveNext() 

Inner exceptions: 
  An exception of type System.Net.Sockets.SocketException was thrown: An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full 
  Stack trace: 
    at Npgsql.NpgsqlClosedState.Open(NpgsqlConnector context, Int32 timeout)

Possible causes

I have not identified a certain cause, but judging by this MSDN blog post it seems that Npgsql either exhausts TCP ephemeral ports or the memory available for TCP buffers.

Reproducing the issue

Sadly, I am unable to share any code. The essence is an EF6 DBContext, connected with pooling enabled (I also use SSL, if that matters), hitting the database eagerly for an extended time period. Eventually, an Open should fail with the error above. The same single instance of the DBContext is used, and async/await is used rather heavily.

Activity

  1. havard commented on Feb 27, 2015

    @havard
    Author

    I have analyzed memory dumps and found that the reason is indeed that NpgsqlConnection instances aren't being cleaned up properly.

    Here is the relevant part of a heap view showing that the StateChangeEventHandler is not properly cleaned up, maintaining an indirect cyclic reference between the NpgsqlConnection and NpgsqlCommand objects.

    image

    I suspect this is the case for all executed commands, meaning that all connections ever made to the database linger in memory.

  2. havard commented on Feb 27, 2015

    @havard
    Author

    The Connection property setter on NpgsqlCommand takes care of adding/removing the relevant event handlers. It seems that cleanup is supposed to happen when NpgsqlCommand.Dispose() is called, by setting the Connection property to null.

    However, EF does not Dispose() DbCommand objects. This is documented several places, e.g. the triage notes for EF issue 2306 (scroll down and read the comment by ajcvickers from Jul 17, 2014 at 6:25 PM).

    Hence, the removal of the event handler has to happen somewhere else.

  3. added this to the 2.2.5 milestone on Feb 27, 2015
  4. roji commented on Feb 27, 2015

    @roji
    Member

    Thanks for raising this and also for the detailed analysis... I'll try to take a look at this ASAP.

  5. roji commented on Feb 28, 2015

    @roji
    Member

    So I've taken a look.

    NpgsqlCommand adds itself to the connection's StateChange event to know about the connection being closed. It needs to do this because part of closing involves deallocating all prepared statements, and prepared commands need to be aware of this (otherwise if the connection is re-opened and the command is executed, it will mistakenly use the prepared statement protocol).

    Unfortunately, the relationship between commands and their relationships needs to persist across connection open/close - we can't unregister the command when its connection is closed.

    So unless I'm missing some alternate solution, this brings us to the subject of weak event handlers... There are a lot of posts on this, from a quick look it seems that Dustin Campbell's solution seems to be the accepted one (see this stackoverflow page). One thing I dislike about this approach is that while invocation performance is good, add/remove performance takes a (considerable?) bump. And with ADO.NET commands there's a chance that adding/removing would happen even more often than invocation (think about single-use commands).

    Since this is a purely internal matter between two Npgsql classes, we can also do a custom non-event-based solution, i.e. have a simple List on NpgsqlConnection holding weak references to all of its active commands. Note that we'd need to manually clean up the weak references themselves from the list even if their command instance has already been garbage-collected.

    Does anybody have any other idea that would allow us to avoid this whole mess?

  6. havard commented on Feb 28, 2015

    @havard
    Author

    I haven't made a deep-dive through the code, but would a lazier approach be possible?

    • A fresh command just prepares its statement when needed.
    • If the connection changes on the command, cleanup prepared statements on the old connection and re-prepare on the new when needed.
    • If the connection closes and reopens, a re-prepare is needed, and should be detectable since the previous prepared statement is no longer there. Just re-prepare when needed, as before.

    An issue may be that connections closing do not cleanup prepared statements. The PostgreSQL docs state:

    If you do not explicitly deallocate a prepared statement, it is deallocated when the session ends.

    If "session ends" means "connection closes", everything should be fine.

  7. roji commented on Mar 1, 2015

    @roji
    Member

    If the connection closes and reopens, a re-prepare is needed, and should be detectable since the previous prepared statement is no longer there. Just re-prepare when needed, as before.

    But that is precisely the point: how do we know, client-side, when a given prepared command needs to be re-prepared? The problem here is what happens with a prepared statement whose connection has been closed and reopened. As you correctly said, on the server side the prepared statement will be automatically deallocated, but at the client side it's still marked as prepared. So if the user attempts to execute the command (without preparing it first), we get an error from the backend (since we tried to execute a prepared command which no longer corresponds to a backend prepared statement).

    Another solution which comes to mind, and which is much simpler than weak event handlers, is simply to record the last closing time on the connection, and the prepare time on the command. Then, when a prepared command is about to be executed, we compare the two timestamps, and if the connection was closed since the prepare we treat the command as a regular unprepared.

  8. havard commented on Mar 1, 2015

    @havard
    Author

    My reasoning assumes that PostgreSQL gives a specific error code for executions of prepared statements which aren't there. To Npgsql, this implies that the connection has changed, enabling Npgsql to make an attempt to re-prepare upon detecting that error.

    Having said that, your fix sounds OK to me and should also be cheaper, since it does not depend on failing and detecting an error upon connection change.

  9. roji commented on Mar 1, 2015

    @roji
    Member

    Your reason is correct, and we would probably be able to identify that error. However, aside from being more expensive (because of the extra roundtrip) errors fail the current transaction in PostgreSQL, meaning that normal logic should never be based upon generating and intercepting an exception...

    As you probably saw I wrote a fix which for some reason breaks on the build server, I'll investigate soon and merge this for the 2.2.5 release.

    Thanks again for bringing this to our attention...

  10. havard commented on Mar 1, 2015

    @havard
    Author

    Ah, the transaction failing didn't cross my mind.

    Glad you found a good solution, looking forward to testing 2.2.5.

  11. roji commented on Mar 1, 2015

    @roji
    Member

    One more note... Actually comparing timestamps makes Npgsql dangerously sensitive to clock changes. But there's a much simpler/cleaner solution: simply increment a counter on NpgsqlConnection each time Open() is called. Copy the current value of this counter to the prepared NpgsqlCommand, and check if they're equal...

    I'll amend the fix and make it work on the build server.

  12. havard commented on Mar 1, 2015

    @havard
    Author

    Great, good solution.

    I also noticed that NpgsqlNetworkStream instances are lingering in the object heap. A fix I've tested that seems to work for me is setting BaseStream = null when closing connections.

  13. added 2 commits that reference this issue on Mar 2, 2015
    54659c9
    257094f
  14. changed the title [-]Resource starvation for long-running tasks[/-] [+]Command never gets garbage allocated if not disposed[/+] on Mar 2, 2015
  15. self-assigned this
    on Mar 2, 2015
  16. 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