Skip to content

Closing connection before reader disposing leads to broken connector #2964

Closed

Description

@alec-anikin

Steps to reproduce

MyMethod()
{
            if (_connection.State != ConnectionState.Open)
            {
                await _connection.OpenAsync(token);
                await _command.PrepareAsync(token);
            }

            using var reader = await _command.ExecuteReaderAsync(token);

            while (await reader.ReadAsync(token))
            {
                ...
                    yield return someResult;
                    
            }

            if (_connection.State != ConnectionState.Closed)
                _connection.Close();

            if (...)
                yield return someResult;
}

The issue

I have 2 Exceptions one by one:

  1. For new opening connection (exception messages can be different)
Npgsql.NpgsqlException (0x80004005): Received backend message BindComplete while expecting ReadyForQueryMessage. Please file a bug.\n  
 at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)\n  
 at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)\n   
at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)\n  
 at Lib.Pgsql.ConnectionExtensions.OpenWithParametersAsync(NpgsqlConnection connection, String defaultSchema)\n  
 at ...
  1. For reader disposing
Npgsql.NpgsqlException (0x80004005): Exception while reading from stream\n ---> System.IO.IOException: Unable to read data from the transport connection: Operation canceled.\n ---> System.Net.Sockets.SocketException (125): Operation canceled\n   
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)\n  
 --- End of inner exception stack trace ---\n   
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)\n   
at Npgsql.NpgsqlReadBuffer.<>c__DisplayClass34_0.<<Ensure>g__EnsureLong|0>d.MoveNext()\n  
at Npgsql.NpgsqlReadBuffer.<>c__DisplayClass34_0.<<Ensure>g__EnsureLong|0>d.MoveNext()\n
--- End of stack trace from previous location where exception was thrown ---\n  
 at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()\n
--- End of stack trace from previous location where exception was thrown ---\n  
 at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()\n
--- End of stack trace from previous location where exception was thrown ---\n 
  at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)\n  
 at Npgsql.NpgsqlDataReader.Consume(Boolean async)\n  
 at Npgsql.NpgsqlDataReader.Close(Boolean connectionClosing, Boolean async)\n 
  at Npgsql.NpgsqlDataReader.Close()\n   at 
SomeClass.MyMethod(...)   at 

And finally this leads to exhausted connection pool.
I got my mistake in the code above but I hope you can make this issue more explicit.

Further technical details

Npgsql version: 4.1.3
PostgreSQL version: 10.7
Operating system: Any

Activity

  1. roji commented on May 21, 2020

    @roji
    Member

    I couldn't reproduce any error with your code, please see the below code sample. Can you please submit a full sample (just like the below) which triggers the error?

    Attempted repro
    class Program
    {
        const string ConnectionString = "Host=localhost;Database=test;Username=test;Password=test";
    
        static async Task Main(string[] args)
        {
            using (var conn = new NpgsqlConnection(ConnectionString))
            using (var cmd = conn.CreateCommand())
            {
                conn.Open();
                cmd.CommandText = @"
    DROP TABLE IF EXISTS data;
    CREATE TABLE data (val INT);
    INSERT INTO data (val) VALUES (4), (5);";
                cmd.ExecuteNonQuery();
            }
            
            var foo = new Foo(ConnectionString);
            await foreach (var i in foo.MyMethod())
            {
                Console.WriteLine(i);
            }
        }
    }
    
    class Foo
    {
        NpgsqlConnection _connection;
        NpgsqlCommand _command;
    
        public Foo(string connectionString)
        {
            _connection = new NpgsqlConnection(connectionString);
            _command = _connection.CreateCommand();
            _command.CommandText = "SELECT * FROM data";
        }
        
        public async IAsyncEnumerable<int> MyMethod(CancellationToken token = default)
        {
            if (_connection.State != ConnectionState.Open)
            {
                await _connection.OpenAsync(token);
                await _command.PrepareAsync(token);
            }
    
            using var reader = await _command.ExecuteReaderAsync(token);
    
            while (await reader.ReadAsync(token))
            {
                yield return reader.GetInt32(0);
            }
    
            if (_connection.State != ConnectionState.Closed)
                _connection.Close();
            // if (...)
            //     yield return someResult;
        }
    }
  2. alec-anikin commented on May 22, 2020

    @alec-anikin
    Author

    Sorry, I should have done it for the first post.

    Reproducible sample
     class Program
        {
            const string ConnectionString =
                "Host=localhost;Database=test;Username=test;Password=test;Maximum Pool Size=10;";
    
            static async Task Main(string[] args)
            {
                var tasks = Enumerable.Range(0, 500)
                    .Select(_ => StartReadAsync());
    
                await Task.WhenAll(tasks);
    
                async Task StartReadAsync()
                {
                    await Task.Yield();
                    try
                    {
                        var foo = new Foo(ConnectionString);
                        await foreach (var i in foo.MyMethod())
                        {
                            //doesn't matter
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
    
        class Foo
        {
            NpgsqlConnection _connection;
            NpgsqlCommand _command;
    
            public Foo(string connectionString)
            {
                _connection = new NpgsqlConnection(connectionString);
                _command = _connection.CreateCommand();
                _command.CommandText = "select * from pg_type";
            }
    
            public async IAsyncEnumerable<string> MyMethod(CancellationToken token = default)
            {
                if (_connection.State != ConnectionState.Open)
                {
                    await _connection.OpenAsync(token);
                    await _command.PrepareAsync(token);
                }
    
                using var reader = await _command.ExecuteReaderAsync(token);
    
                while (await reader.ReadAsync(token))
                {
                    yield return reader.GetString(0);
                }
    
                //Connector released
                _connection.Close();
    
                await Task.Delay(100, token);
    
                //Reader disposed/closed here and will read from released connector
            }
        }
    
  3. roji commented on May 22, 2020

    @roji
    Member

    Thanks, that repros for me - will definitely look into this right away.

  4. added this to the 4.1.4 milestone on May 31, 2020
  5. self-assigned this
    on May 31, 2020
  6. warcha commented on Jul 9, 2020

    @warcha
    Contributor

    Hi @roji, @YohDeadfall,

    I had a look at this issue to try and fix this but unfortunately I don't know enough about the NpgsqlDataReader and NpgsqlConnection (trying to learn and get a better understanding). I think the exceptions listed above are getting thrown as the reproducible sample provided has a few incorrect / missing declarations.

    I think the things that need to be fixed in the reproducible sample provided are:

    • The CancellationToken parameter for MyMethod needs to be marked with the [EnumeratorCancellation] attribute
      public async IAsyncEnumerable<string> MyMethod([EnumeratorCancellation] CancellationToken token = default)

    • The using statement needs to be prefixed with await in order to work with IAsyncEnumerable and IAsyncDisposable instances (I found that without the await prefix, the NpgsqlDataReader Dispose method was being called instead of the DisposeAsync)
      await using var reader = await _command.ExecuteReaderAsync(token);
      Details on prefixing await to using statements can be found here

    • when closing the connection, the CloseAsync() method needs to be called instead of Close()
      await _connection.CloseAsync();

    Once, these changes are made to the reproducible sample, the exceptions listed no longer get thrown, however, I do start getting the following exceptions:
    System.InvalidOperationException: The reader is closed at Npgsql.NpgsqlDataReader.ReadAsync(CancellationToken cancellationToken) in C:\Work\git\OSS\npgsql\src\Npgsql\NpgsqlDataReader.cs:line 179

    Looking into this exception, I can see that on a NpgsqlConnection.CloseAsync(), the connector.CloseOngoingOperations(async) method is called which in turn looks to close any open readers on that connection.

    On the reader.ReadAsync, the first thing that is done is the connection is checked if closed, if closed, the InvalidOperationException is thrown.

    My understanding here in relation to the NpgsqlConnection here is a little bit sketchy so I'm unsure of what the behavior of the NpgsqlDataReader is meant to be when the connection is closed? Is the dataReader meant to still be available even if the connection has been closed? Is this expected behavior?

  7. YohDeadfall commented on Jul 18, 2020

    @YohDeadfall
    Contributor

    @warcha, a reader must be closed if the corresponding connection is closed because all resources are freed: no socket to read data.

    Sorry for taking so long to reply, was on vacation and slowly going through my mail box (:

  8. YohDeadfall commented on Jul 18, 2020

    @YohDeadfall
    Contributor

    When the Close method gets called on the connection, firstly it should finish the reader too by fetching all data from it. If the reader gets - disposed after the connection, there should be no operations. Therefore, the issue looks correct to me.

  9. modified the milestones: 4.1.4, 4.1.5 on Jul 19, 2020
  10. warcha commented on Jul 20, 2020

    @warcha
    Contributor

    Thanks for the explanation @YohDeadfall, hope you had a good vacation (:

  11. warcha commented on Jul 22, 2020

    @warcha
    Contributor

    Hi @YohDeadfall, I've been looking at this issue and I'm a little out of my depth here so apologies in advance for any silly questions (trying to learn and understand the inner workings).

    So my understanding is that if the connection is closed before the reader is disposed, any pending operations on the reader need to be completed (which in an asynchronous environment means that all existing aysnc tasks need to be completed before the connection can be closed?).

    From what I can see in the code, when _connection.CloseAsync() is called, it checks if the connector is still in a transaction (connector.InTransaction) and if it is, it calls connector.CloseOngoingOperations(async). This ends up calling a CleanUp task on the NpgsqlDataReader which then calls await _sendTask before setting the State = ReaderState.Closed for the Reader.
    Not sure if this is a silly question but will await _sendTask on the NpgsqlDataReader wait till all the existing async tasks currently open on the reader complete? If not then how do we ensure all running tasks are completed before setting State = ReaderState.Closed on the reader?

    Thanks in advance for any guidance on this.

  12. YohDeadfall commented on Jul 22, 2020

    @YohDeadfall
    Contributor

    Am not very familiar with this part of the code, need to learn it too. @roji, could you explain how should it work and how does it work now?

  13. roji commented on Jul 27, 2020

    @roji
    Member

    @warcha regarding your 3 comments in #2964 (comment):

    The CancellationToken parameter for MyMethod needs to be marked with the [EnumeratorCancellation] attribute [...]
    The using statement needs to be prefixed with await in order to work with IAsyncEnumerable and IAsyncDisposable instances [...]
    when closing the connection, the CloseAsync() method needs to be called instead of Close() [...]

    You're right that the sample isn't fully async etc., but it still seems to reproduce a bug in Npgsql - unless you're seeing anything in that sample which seems actually incorrect. It's indeed interesting that when the sample is made properly async the error disappears, but that could simply be because the sample as-is exposes a race condition which doesn't manifest itself when the code is made async. Regarding the 2nd error, which occurs after changing the sample to be async, it may or may not be related - I'd concentrate on one error at a time (starting with whichever one you want).

  14. 8 remaining items

  15. warcha commented on Aug 5, 2020

    @warcha
    Contributor

    Hi @roji, I've been looking at this for a little while now and unfortunately I've not been able to figure this one out. In either a multi threaded or asynchronous application, I can see that in some instances when disposing of the reader (after the connection has been closed) that the connectors ConnectorState is "Executing" (I think the state is meant to be "Fetching" at this point when being disposed) which results in an await Consume() not returning the expected ReadyForQuery message (usually in this instance it is DataRow or BindComplete). I've been looking at this and can't figure out how it gets into this state as explicitly closing the connection calls the connectors CloseOnGoingOperations which should complete any current calls. I've tried a few things but my understanding of this area is limited and I've got to a point where I can't seem to make any further headway. Probably best if you took over from here and had a look, really sorry I couldn't find a resolution to this issue.

  16. YohDeadfall commented on Aug 5, 2020

    @YohDeadfall
    Contributor

    No worries (: Me or Shay will take care about this.

  17. warcha commented on Aug 5, 2020

    @warcha
    Contributor

    Thanks @YohDeadfall, really disappointed I couldn't resolve this. Really keen to see what the issue is though.

  18. roji commented on Aug 6, 2020

    @roji
    Member

    Npgsql isn't trivial, and concurrency issues are the worst thing in the world of programming :) @YohDeadfall let me know if you don't intend to work on this, it seems like it could be quite important.

  19. vonzshik commented on Aug 9, 2020

    @vonzshik
    Contributor

    @warcha I have an idea:

    1. First thread closed NpgsqlConnection inside opened NpgsqlDataReader
    2. On closing connection it returns to the pool and NpgsqlDataReader is also closed
    3. Second thread takes this connection and begins using NpgsqlDataReader (it's the same one the first thread has)
    4. First thread tries to dispose NpgsqlDataReader, it's opened from second thread, so we need to read everything
    5. Two threads read from same NpgsqlDataReader
  20. vonzshik commented on Aug 10, 2020

    @vonzshik
    Contributor

    This test should represent the problem

    [Test]
    public async Task ReusingClosedConnectionReaderTest()
    {
    	// Opening new connection from the pool
    	using var firstConnection = OpenConnection();
    	var firstCommand = firstConnection.CreateCommand();
    	firstCommand.CommandText = "SELECT 1";
    	var firstReader = firstCommand.ExecuteReader();
    	firstReader.Read();
    	// Closing connection, returning it to the pool
    	firstConnection.Close();
    
    	// Opening new connection from the pool (but it's actually the first connection)
    	using var secondConnection = OpenConnection();
    	var secondCommand = secondConnection.CreateCommand();
    	secondCommand.CommandText = "SELECT 1";
    	// Executing new reader (but it's actually the first reader)
    	var secondReader = secondCommand.ExecuteReader();
    
    	// Closing the first reader (and impicitly the second)
    	await firstReader.DisposeAsync();
    
    	// Failing, as reader is closed
    	secondReader.Read();
    }
  21. warcha commented on Aug 10, 2020

    @warcha
    Contributor

    Thanks @vonzshik, I didn't think of that scenario but it makes sense. And thanks for the test, I'll have another look at this.

  22. YohDeadfall commented on Sep 21, 2020

    @YohDeadfall
    Contributor

    @vonzshik, your example shows incorrect usage of the driver because of it internals. At the same time, the scenario is correct because the user should not know internals of the driver. I think the proper fix is to stop caching NpgsqlDataReader because it's cheap enough to allocate a small chunk of memory.

    @roji, your opinions here?

  23. roji commented on Sep 24, 2020

    @roji
    Member

    I've been wanting to look into this for a while now - will do so very soon.

  24. warcha commented on Sep 24, 2020

    @warcha
    Contributor

    My apologies for not looking into this yet. I've got some really urgent things on my plate at the moment and just haven't had a chance to look into anything else, i'm hoping to be able to soon but I think it won't be for another couple of weeks.

  25. modified the milestones: 4.1.5, Backlog on Sep 28, 2020
  26. added a commit that references this issue on Nov 15, 2020
    7bb2617
  27. 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

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions