Repository navigation
Closed
Milestone
Description
Dear Team,
I'm using Npgsql 2.1.3 and get the exception when being subscribed for Listen/Notify events. The exception happens when some command is invoked and async notification arrives at the same time, but it does not happen always.
Here goes the message and stacktrace:
An unhandled exception of type 'System.NotSupportedException' occurred in Npgsql.dll
Additional information: Cannot write to a BufferedStream while the read buffer is not empty if the underlying stream is not seekable. Ensure that the stream underlying this BufferedStream can seek or avoid interleaving read and write operations on this BufferedStream.
at System.IO.BufferedStream.WriteByte(Byte value)
at Npgsql.NpgsqlQuery.WriteToStream(Stream outputStream)
at Npgsql.NpgsqlReadyState.Query(NpgsqlConnector context, NpgsqlQuery query)
at Npgsql.NpgsqlConnector.Query(NpgsqlQuery query)
at Npgsql.NpgsqlCommand.GetReader(CommandBehavior cb)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior cb)
at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
at NpgsqlNotifyTest.Program.<>c__DisplayClass6.<Main>b__3() in d:\NpgsqlNotifyTest\NpgsqlNotifyTest\Program.cs:line 27
at System.Threading.ThreadHelper.ThreadStart_Context(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.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()Please use following code to reproduce the issue (it takes a couple of seconds - just leave it running).
using System.Data;
using System.Diagnostics;
using System.Threading;
using Npgsql;
namespace NpgsqlNotifyTest
{
class Program
{
static void Main(string[] args)
{
var builder = new NpgsqlConnectionStringBuilder { Host = "127.0.0.1", Database = "postgres", UserName = "postgres" };
var thread1 = new Thread(() =>
{
var connection1 = new NpgsqlConnection(builder);
connection1.Open();
connection1.Notification += (sender, e) => Debug.WriteLine("NOTIFICATION RECEIVED [{1}] {0}", e.Condition, e.PID);
var command1 = new NpgsqlCommand { Connection = connection1, CommandText = "LISTEN marek" };
command1.ExecuteNonQuery();
command1.CommandText = "select * from pg_class";
while (true)
{
var da = new NpgsqlDataAdapter(command1);
da.Fill(new DataTable());
Thread.Sleep(1000);
}
});
thread1.Start();
var thread2 = new Thread(() =>
{
var connection2 = new NpgsqlConnection(builder);
connection2.Open();
var command2 = new NpgsqlCommand { Connection = connection2, CommandText = "NOTIFY marek" };
while (true)
{
command2.ExecuteNonQuery();
Thread.Sleep(100);
}
});
thread2.Start();
thread1.Join();
}
}
}Thanks in advance for checking above issue if it's a bug.
Regards,
Marek
Activity
franciscojunior commentedon Jun 6, 2014
Hi, @solar-soft !
Thank you for your test! It will help us check where the problem is!
I'll have a look at it.
roji commentedon Sep 15, 2014
Note that we're planning a rewrite of async notifications (#270) which should among other things make this bug go away. Am leaving to use the test here after the rewrite happens.
akontsevich commentedon Dec 5, 2014
I have same error on heavy load operations: many requests for same service simultaneously. Not reproducible in normal operations. Will watch for this bug, hope You'll able to fix it quick. My error stack is:
I have no notification event, so I want to say there are many reasons for this error. Seems exists in all 2.x versions, however was able to identify it only in 2.2.3. I have 4.0 .Net version. We encounter problems with using Npgsql on heavy load operations for a long time: previously it were thread synchronization error (seems you have partially fixed them), now above error:
And notifications are not invoked in our case.
P.S. Other question: are there some temporal workaround available like connection string settings, poling settings, etc?
franciscojunior commentedon Dec 12, 2014
It seems data is being held in the networkstream used by Npgsql. BufferedStream checks if all the data in its buffers were consumed before writing to it.
This may be caused by a bug in Npgsql protocol state machine handling. Under heavy load, there may appear some corner cases where this data is not consumed properly.
Another possibility is that the client code may not be consuming all the data from Npgsql before sending queries to the server.
I remember we received some reports about those problems, but as you said, they were very difficult to reproduce and we couldn't find the source of this problem.
In your specific case, those exceptions appear in only one place in your code or is it random?
Your case could help us identify a possible context where those exceptions appear. If you could consistently get those exceptions, it would be of great help if you could identify some patterns (work load, previous operations, type of operations) which would be present at the time of the problem.
Thanks in advance for any information.
akontsevich commentedon Dec 13, 2014
@franciscojunior It appeared in one place. Additional information: under heavy load a very often invoked service (probably ServiceStack creates separate thread for each POST) which produced an error, this was logged into postgresql. I was using here my internal logging class which calls stored procedure (function), I can post their code here. When I have replaced my logging to NLog here, Npgsql error disappeared.
So I can post call stack and the code here, as I said we use .Net 4.0.
Call stack:
Calling Log from the service:
Log.Warning(warningMessage, string.Format("UserId: {0}, contactIdLocal: {1}", request.UserId, contactIdLocal));Log class method:
PgDataAccess class:
ExecuteNonQuery calls following SQL function:
franciscojunior commentedon Dec 13, 2014
Thanks for the info, @akontsevich !
One question: where does your PgDataAccess object get the NpgsqlConnection to run its queries?
I suppose it would be in the PrepareCommand() method. Can you post its code, please?
Thanks in advance.
franciscojunior commentedon Dec 13, 2014
I just noticed that I may be hijacking this issue report. Sorry about that.
@akontsevich , would you mind to continue our conversation in our users forum, please? https://groups.google.com/forum/#!forum/npgsql-help
Your feedback will be very important to us.
Thanks in advance.
akontsevich commentedon Dec 13, 2014
@franciscojunior, I've created following topic: https://groups.google.com/forum/#!topic/npgsql-help/ViuGNdazb5Y Thanks!
mlb5000 commentedon Dec 23, 2014
I'm also getting this error when attempting to use Npgsql from a HangFire background job.
franciscojunior commentedon Dec 24, 2014
@mlb5000 , are you trying to use the same connection inside your notification handler? If so, this may be your problem. Npgsql, as other .net providers, isn't thread safe. Try using a different connection.
I hope it helps.
realityexists commentedon Feb 25, 2015
We've also been running into this issue (intermittently) using Npgsql 2.0.14.3. Strangely, it's only appeared recently, though we'd been using 2.0.14.3 for some time. Has anyone figured out a workaround?
mlb5000 commentedon Feb 25, 2015
@realityexists Yes we did, though it might actually be what is required rather than a workaround. In addition to the normal values in the connection string we had to add this:
;POOLING=True;MINPOOLSIZE=10;Preload Reader=truerealityexists commentedon Feb 25, 2015
Thanks. Which of those settings makes the difference, though - MinPoolSize or Preload Reader or both of them together somehow? If so, do you know how? (Pooling=true is the default according to the user guide.)
5 remaining items
Emill commentedon Mar 3, 2015
The intention is to watch with DataAvailable property after each operation to see if there is any pending notification and process it if so, so it shouldn't be necessary to use double buffers...
Emill commentedon Mar 3, 2015
I fixed in master so it now drains the buffer correctly after a query.
ChenHuajun commentedon Mar 16, 2015
Hi @Emill,Your are right in theory. There is no problem if we ensure "the buffer had been drained correctly before any TCP send". But i don't known whether it is easy to implement in fact. Whether all patterns had been considered correctly. (As far as i known some query may contains more than once read/write TCP communication).
And we also must remember the rule "the buffer had been drained correctly before any TCP send" in future source modification.(Just like we must remember the rule "free all memory your allocated" in C)
Maybe i'm wrong,i am not so familiar with the Npgsql's source, and the rule "the buffer had been drained correctly before any TCP send" maybe easy to be satisfed.
roji commentedon Apr 15, 2015
@ChenHuajun, I've merged your test and as expected things work fine at the moment.
I think that @Emill's solution is OK - make sure the read buffer is drained before switching the connector state to Ready (and allowing a new messages to be written). However, the current implementation has a few issues, I've opened #578 for this.
roji commentedon Apr 20, 2016
Small note for 3.1: since (at least for now) we're going to solve the multistatement deadlock problem in #641 by using async writes, we need double buffers (send and receive). Therefore, it's no longer necessary to make sure buffers are drained etc.