Skip to content

NpgsqlDataAdapter fills invalid data when using pooled connections and concurrency #2644

Closed

Description

@NikoHellgren

The issue

If the connection has been configured to use pooling, heavily concurrent use of NpgsqlDataAdapter places the text "pg_advisory_unlock_all" to the filled DataSet's table column at some point, instead of the expected column name. Also, instead of having the expected int32 value 1 in the row, there is a string "\0\0\0\u0001" in its place.
This started happening when I updated to 4.1.0. All 4.0.x versions have worked just fine.

Steps to reproduce

I reproduced the issue with the following sample code.
Table definition:

CREATE TABLE myschema.postgres_test_table (
	id int4 NULL
);
INSERT INTO myschema.postgres_test_table
(id)
VALUES(1);

C# code:

class Program
    {
        private const string _connectionString = "Host=localhost;Port=5432;Username=admin;Password=pass;Database=sample_db;Connection Idle Lifetime=30;Command Timeout=300;Timeout=120;Max Auto Prepare=250;Pooling=False;Maximum Pool Size=95";
        static void Main(string[] args)
        {
            Parallel.For(0, 100, _ => ReadIdFromDb());

            Console.ReadKey();
            
        }

        private static void ReadIdFromDb()
        {
            DataTable t = null;
            string query = @"SELECT id FROM myschema.postgres_test_table";

            using (NpgsqlConnection conn = GetOpenConnection())
            using (var cmd = new NpgsqlCommand(query, conn) { CommandType = CommandType.Text })
            {

                using (var da = new NpgsqlDataAdapter(cmd))
                {
                    var ds = new DataSet();
                    da.Fill(ds);
                    t = ds.Tables[0];
                }
                conn.Close();
            }
            if (t.Columns[0].Caption != "id")
            {
                // This will throw eventually
                throw new Exception($"Invalid column caption, expected \"id\", was \"{t.Columns[0].Caption}\"");
            }
        }

        private static NpgsqlConnection GetOpenConnection()
        {
            var conn = new NpgsqlConnection(_connectionString);
            conn.Open();

            return conn;
        }
    }

Further technical details

Npgsql version: 4.1.0
Runtime version: .NET Core 2.1 (initially discovered in .NET Framework 4.7.2)
PostgreSQL version: 11.2
Operating system: Windows 10, version 1809

Activity

  1. roji commented on Sep 27, 2019

    @roji
    Member

    @NikoHellgren FWIW your repro runs without any issues on my machine... Does the error happen regularly/deterministically? I'll also try from a stronger machine on Monday, as this kind of issue is very environment-sensitive.

    Also, could you please try removing the Pooling=false and/or Max Auto Prepare from the connection string and report on the result?

  2. Nikheln commented on Sep 27, 2019

    @Nikheln

    (different account) I tested this again with my personal laptop, and with a clean installation of PostgreSQL I was unable to reproduce this as well. This phenomenon broke our tests in three different machines, so it probably has something to do with our PostgreSQL configuration. When run with pooling disabled, the issue did not reproduce (at least in my initial tests, I already tried this out since the only place I could find in Npgsql code that uses "pg_advisory_unlock_all" is affected by the pooling option). Similarly, when downgrading back to 4.0.10, the issue disappeared.
    I'll look into it more on Monday and try to pinpoint the exact cause of this behaviour.
    Edit: And yes, the error happens on every run I've tried.

  3. roji commented on Sep 27, 2019

    @roji
    Member

    Thank you for the added details. As you've noticed, pg_advisory_unlock_all is only ever emitted by Npgsql when pooling is on and when auto-prepared statements are enabled (Max Auto Prepared > 0). Let me know what you find, if there's some way that I can see this happening here I can investigate it further.

  4. NikoHellgren commented on Sep 30, 2019

    @NikoHellgren
    Author

    I spent some time debugging and testing this issue, and found some additional info:

    • Despite my initial example using parallelism and NpgsqlDataAdapter, after further testing I have found that the issue was reproducible even without parallelism (an ordinary for-loop) and even with NpgsqlDataReader (our application heavily uses NpgsqlDataAdapter, so that's where I initially discovered the problem).
    • I recreated the DB from scratch (initdb with only the directory and superuser specified + pg_ctl to run it), and the issue still reproduced on my work laptop and our testing environment. These same steps did not cause the issue to repro on my personal computer as stated earlier.
    • When using an ordinary for-loop, the error consistently happened on the 6th iteration of the command, and on all subsequent queries. Given the following test code, the first iteration of the outer loop failes when j=5, and all subsequent rounds fail with j=0:
    for (int i = 0; i < 1000; i++)
    {
    	int j = -1;
    	try
    	{
    		for (j = 0; j < 100; j++)
    		{
    			ReadIdFromDb();
    		}
    	}
    	catch
    	{
    		Console.WriteLine("Query failed in iteration " + j);
    	}
    }
    
    ...
    
    using (NpgsqlConnection conn = GetOpenConnection())
    using (var cmd = new NpgsqlCommand(query, conn) { CommandType = CommandType.Text })
    {
    	NpgsqlDataReader reader = cmd.ExecuteReader();
    	reader.Read();
    
    	ReadOnlyCollection<Npgsql.Schema.NpgsqlDbColumn> columns = reader.GetColumnSchema();
    	if (columns[0].ColumnName != "id")
    	{
    		throw new Exception($"Invalid column caption, expected \"id\", was \"{columns[0].ColumnName}\"");
    	}
    
    	reader.Close();
    	conn.Close();
    }
    

    This behaviour seems to be bound to auto-preparation, as increasing Auto Prepare Min Usages from the default value of 5 to anything else increases the amount of loops required.

    Edit: The existing RowDescriptionMessage referred to by the (auto-prepared) NpgsqlStatement of the query seems to be mutated by the following call stack when the prepended messages are being read by ReadMessageLong. The RowDescriptionMessage object that the Load method is invoked on appears to be the same as the one used by the statement object.
    Why this happens only on my work laptop and not my personal one, I cannot say, as reusing the NpgsqlConnector::_rowDescriptionMessage is the intended approach to loading these.

    Npgsql.dll!Npgsql.BackendMessages.RowDescriptionMessage.Load(Npgsql.NpgsqlReadBuffer buf, Npgsql.TypeMapping.ConnectorTypeMapper typeMapper) Line 41	C#
    Npgsql.dll!Npgsql.NpgsqlConnector.ParseServerMessage(Npgsql.NpgsqlReadBuffer buf, Npgsql.BackendMessageCode code, int len, bool isPrependedMessage) Line 974	C#
    Npgsql.dll!Npgsql.NpgsqlConnector.DoReadMessage.__ReadMessageLong|0(Npgsql.DataRowLoadingMode dataRowLoadingMode2, bool readingNotifications2, bool isReadingPrependedMessage) Line 902	C#
    Npgsql.dll!Npgsql.NpgsqlConnector.DoReadMessage.__ReadMessageLong|0(Npgsql.DataRowLoadingMode dataRowLoadingMode2, bool readingNotifications2, bool isReadingPrependedMessage) Line 858	C#
    Npgsql.dll!Npgsql.NpgsqlConnector.DoReadMessage(bool async, Npgsql.DataRowLoadingMode dataRowLoadingMode, bool readingNotifications) Line 821	C#
    Npgsql.dll!Npgsql.NpgsqlConnector.ReadMessage(bool async, Npgsql.DataRowLoadingMode dataRowLoadingMode) Line 806	C#
    Npgsql.dll!Npgsql.NpgsqlDataReader.NextResult(bool async, bool isConsuming) Line 396	C#
    Npgsql.dll!Npgsql.NpgsqlDataReader.NextResult() Line 298	C#
    Npgsql.dll!Npgsql.NpgsqlCommand.ExecuteReaderAsync(System.Data.CommandBehavior behavior, bool async, System.Threading.CancellationToken cancellationToken) Line 1165	C#
    Npgsql.dll!Npgsql.NpgsqlCommand.ExecuteReader(System.Data.CommandBehavior behavior) Line 1047	C#
    Sandbox.dll!Sandbox.Program.ReadIdFromDb() Line 46	C#
    Sandbox.dll!Sandbox.Program.Main(string[] args) Line 25	C#
    
  5. roji commented on Sep 30, 2019

    @roji
    Member

    Thanks for continuing to look into this, and for the analysis. This led me to uncover a bug introduced in 4.1.0, where we started recycling the RowDescription instance (to reduce allocations), and cloned a private copy for explicitly-prepared statements, but aren't doing this for auto-prepared ones.

    See #2654 for the fix. Can you please test and CI nuget with version 5.0.0-ci.2379 from the unstable feed?

  6. NikoHellgren commented on Sep 30, 2019

    @NikoHellgren
    Author

    Thanks for the quick fix. The issue did not repro with the unstable NuGet.

  7. roji commented on Sep 30, 2019

    @roji
    Member

    Thanks for the quick test! This will be part of 4.1.1 which should come out in the next couple days.

  8. added this to the 4.1.1 milestone on Sep 30, 2019
  9. added 2 commits that reference this issue on Sep 30, 2019
    44ffb8f
    4f2b8e7
  10. 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