Skip to content

NotSupportedException when using async notifications #252

Closed

Description

@solar-soft

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

  1. franciscojunior commented on Jun 6, 2014

    @franciscojunior
    Member

    Hi, @solar-soft !

    Thank you for your test! It will help us check where the problem is!
    I'll have a look at it.

  2. added this to the milestone on Aug 4, 2014
  3. roji commented on Sep 15, 2014

    @roji
    Member

    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.

  4. akontsevich commented on Dec 5, 2014

    @akontsevich

    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:

    at System.IO.BufferedStream.ClearReadBufferBeforeWrite()
    at System.IO.BufferedStream.Write(Byte[] array, Int32 offset, Int32 count)
    at Npgsql.PGUtil.WriteBytes(Stream stream, Byte[] the_bytes)
    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.ExecuteNonQuery()

    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:

    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.

    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?

  5. franciscojunior commented on Dec 12, 2014

    @franciscojunior
    Member

    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.

  6. akontsevich commented on Dec 13, 2014

    @akontsevich

    @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:

    Error: 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.ClearReadBufferBeforeWrite()
       at System.IO.BufferedStream.Write(Byte[] array, Int32 offset, Int32 count)
       at Npgsql.PGUtil.WriteBytes(Stream stream, Byte[] the_bytes)
       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.ExecuteNonQuery()
       at DbFramework.PgDataAccess.ExecuteNonQuery(CommandType type, String query, NpgsqlParameter[] parameters) 
            in C:\...\src\DbFramework\PgDataAccess.cs:line 323
       at DbFramework.PgDataAccess.ExecuteNonQuery(String query, Object[] parameters) 
            in C:\...\src\DbFramework\PgDataAccess.cs:line 294
       at DbFramework.Log.AddRecord(String level, String message, Exception e, String args, String type) 
            in C:\...\src\DbFramework\Log.cs:line 105
       at DbFramework.Log.Warning(String message, String args, String type) 
            in C:\...\src\DbFramework\Log.cs:line 43
       at RestServices.Services.JobLogService.OnPost(SOmeRequest request) 
            in C:\...\src\RestServices\Services\JobLogService.cs:line 49
    

    Calling Log from the service:
    Log.Warning(warningMessage, string.Format("UserId: {0}, contactIdLocal: {1}", request.UserId, contactIdLocal));

    Log class method:

        public class Log
        {
            private static PgDataAccess da = new PgDataAccess();
    
            public static void Warning(string message, string args = null, string type = null)
            {
                AddRecord("WARNING", message, null, args, type);
            }
    
            private static void AddRecord(string level, string message, Exception e = null, string args = null, string type = null)
            {
    //...
                        da.ExecuteNonQuery("add_log_record", level, function, args, message, details, logger, type);
    //...
            }
        }

    PgDataAccess class:

            public int ExecuteNonQuery(string query, params object[] parameters)
            {
                CommandType type = GetCommandType(query);
    
                if ((parameters != null) && (parameters.Length > 0))
                {
                    NpgsqlParameter[] pgParameters = PrepareParameters(parameters);
                    return ExecuteNonQuery(type, query, pgParameters);
                }
                else
                {
                    return ExecuteNonQuery(type, query);
                }
            }
    
            public int ExecuteNonQuery(CommandType type, string query, params NpgsqlParameter[] parameters)
            {
                try
                {
                    NpgsqlCommand command = PrepareCommand(type, query, parameters);
                    int result = command.ExecuteNonQuery();
                    return result;
                }
                catch (Exception e)
                {
                    LogError(e);
                    throw e;
                }
            }

    ExecuteNonQuery calls following SQL function:

    CREATE OR REPLACE FUNCTION add_log_record(level character varying, function character varying, arguments text, message text, details text, logger text, type character varying DEFAULT NULL::character varying, file character varying DEFAULT NULL::character varying)
      RETURNS void AS
    $BODY$
    
        INSERT INTO log (level, function, arguments, message, details, logger, type, processed_file_uuid) 
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8);
    
    $BODY$
      LANGUAGE sql VOLATILE
      COST 100;
  7. franciscojunior commented on Dec 13, 2014

    @franciscojunior
    Member

    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.

  8. franciscojunior commented on Dec 13, 2014

    @franciscojunior
    Member

    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.

  9. mlb5000 commented on Dec 23, 2014

    @mlb5000

    I'm also getting this error when attempting to use Npgsql from a HangFire background job.

  10. franciscojunior commented on Dec 24, 2014

    @franciscojunior
    Member

    @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.

  11. realityexists commented on Feb 25, 2015

    @realityexists

    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?

  12. mlb5000 commented on Feb 25, 2015

    @mlb5000

    @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=true

  13. realityexists commented on Feb 25, 2015

    @realityexists

    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.)

  14. 5 remaining items

  15. Emill commented on Mar 3, 2015

    @Emill
    Contributor

    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...

  16. Emill commented on Mar 3, 2015

    @Emill
    Contributor

    I fixed in master so it now drains the buffer correctly after a query.

  17. ChenHuajun commented on Mar 16, 2015

    @ChenHuajun
    Contributor

    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.

  18. modified the milestones: , 3.0-beta1 on Mar 30, 2015
  19. roji commented on Apr 15, 2015

    @roji
    Member

    @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.

  20. modified the milestones: 3.0-beta1, on Aug 7, 2015
  21. roji commented on Apr 20, 2016

    @roji
    Member

    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.

  22. 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

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions