Repository navigation
Milestone
Description
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:
- 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 ...
- 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
Metadata
Metadata
Assignees
Labels
No labels
Activity
roji commentedon May 21, 2020
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
alec-anikin commentedon May 22, 2020
Sorry, I should have done it for the first post.
Reproducible sample
roji commentedon May 22, 2020
Thanks, that repros for me - will definitely look into this right away.
warcha commentedon Jul 9, 2020
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
awaitin order to work with IAsyncEnumerable and IAsyncDisposable instances (I found that without theawaitprefix, 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 179Looking into this exception, I can see that on a
NpgsqlConnection.CloseAsync(), theconnector.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?
YohDeadfall commentedon Jul 18, 2020
@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 (:
YohDeadfall commentedon Jul 18, 2020
When the
Closemethod 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.warcha commentedon Jul 20, 2020
Thanks for the explanation @YohDeadfall, hope you had a good vacation (:
warcha commentedon Jul 22, 2020
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 callsconnector.CloseOngoingOperations(async). This ends up calling aCleanUptask on the NpgsqlDataReader which then callsawait _sendTaskbefore setting theState = ReaderState.Closedfor the Reader.Not sure if this is a silly question but will
await _sendTaskon 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 settingState = ReaderState.Closedon the reader?Thanks in advance for any guidance on this.
YohDeadfall commentedon Jul 22, 2020
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?
roji commentedon Jul 27, 2020
@warcha regarding your 3 comments in #2964 (comment):
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).
8 remaining items
warcha commentedon Aug 5, 2020
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.
YohDeadfall commentedon Aug 5, 2020
No worries (: Me or Shay will take care about this.
warcha commentedon Aug 5, 2020
Thanks @YohDeadfall, really disappointed I couldn't resolve this. Really keen to see what the issue is though.
roji commentedon Aug 6, 2020
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.
vonzshik commentedon Aug 9, 2020
@warcha I have an idea:
NpgsqlConnectioninside openedNpgsqlDataReaderNpgsqlDataReaderis also closedNpgsqlDataReader(it's the same one the first thread has)NpgsqlDataReader, it's opened from second thread, so we need to read everythingNpgsqlDataReadervonzshik commentedon Aug 10, 2020
This test should represent the problem
warcha commentedon Aug 10, 2020
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.
YohDeadfall commentedon Sep 21, 2020
@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
NpgsqlDataReaderbecause it's cheap enough to allocate a small chunk of memory.@roji, your opinions here?
roji commentedon Sep 24, 2020
I've been wanting to look into this for a while now - will do so very soon.
warcha commentedon Sep 24, 2020
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.
Fixed reading by reader previous query messages