Skip to content

Program crash with transaction and massive insert operation. #1838

Closed

Description

@guogangj

Steps to reproduce

First create a table like this:

        CREATE TABLE user_extra(
            id              BIGSERIAL PRIMARY KEY,
            sex             VARCHAR(10),
            province        VARCHAR(100),
            city            VARCHAR(100),
            country         VARCHAR(100),
            has_subscribed  BOOLEAN,
            subscribe_time  TIMESTAMP
        );

Then run this method. Of course, don't forget to change your database connection string.

        static void MassInsertTest() {
            string connectionStr = "write your PostgreSQL connection string here";
            int iCount = 0; //make an indicator
            try {
                using (NpgsqlConnection conn = new NpgsqlConnection(connectionStr)) {
                    conn.Open();
                    using (TransactionScope ts = new TransactionScope()) {
                        conn.EnlistTransaction(Transaction.Current);
                        for (int i = 0; i < 1000000; i++) {
                            using (var cmd = new NpgsqlCommand()) {
                                cmd.Connection = (NpgsqlConnection)conn;
                                cmd.CommandText = "insert into user_extra (sex, province, city, country, has_subscribed, subscribe_time) values('M', 'ABCD', 'EFG', 'XYZ', true, LOCALTIMESTAMP)";
                                cmd.ExecuteNonQuery();
                            }
                            iCount++;
                            if (iCount % 100 == 0) {
                                Console.WriteLine("=>" + iCount);
                            }
                        }
                        ts.Complete();
                    }
                }
            }
            catch (Exception ex) {
                //No exception will be catched.
                Console.WriteLine(ex);
            }
        }

The issue

As you see above, I insert massive rows to a table and roll these operations in a transaction. I found the program always crashed at about 11000 rows inserted with message like this:

An unhandled exception of type 'Npgsql.NpgsqlOperationInProgressException' occurred in mscorlib.dll
A command is already in progress: insert into user_extra (sex, province, city, country, has_subscribed, subscribe_time) values('M', 'ABCD', 'EFG', 'XYZ', true, LOCALTIMESTAMP)

If I use tranditional .NET Framework, I can get additional stack trace info in the Visual Studio's output window:

System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>未处理的异常</Description><AppDomain>Njt.RdbmsLibDemo.exe</AppDomain><Exception><ExceptionType>Npgsql.NpgsqlOperationInProgressException, Npgsql, Version=3.2.7.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7</ExceptionType><Message>A command is already in progress: insert into user_extra (sex, province, city, country, has_subscribed, subscribe_time) values('M', 'ABCD', 'EFG', 'XYZ', true, LOCALTIMESTAMP)</Message><StackTrace>   在 Npgsql.NpgsqlConnector.StartUserAction(ConnectorState newState, NpgsqlCommand command)
   在 Npgsql.NpgsqlConnector.Rollback(Boolean async, CancellationToken cancellationToken)
   在 Npgsql.NpgsqlTransaction.&amp;lt;Rollback&amp;gt;d__21.MoveNext()
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
   在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   在 Npgsql.NpgsqlTransaction.Rollback()
   在 Npgsql.NpgsqlTransaction.Dispose(Boolean disposing, Boolean doRollbackIfNeeded)
   在 Npgsql.NpgsqlTransaction.Dispose(Boolean disposing)
   在 System.Data.Common.DbTransaction.Dispose()
   在 Npgsql.VolatileResourceManager.Dispose()
   在 Npgsql.VolatileResourceManager.Rollback(Enlistment enlistment)
   在 System.Transactions.VolatileEnlistmentAborting.EnterState(InternalEnlistment enlistment)
   在 System.Transactions.VolatileEnlistmentActive.InternalAborted(InternalEnlistment enlistment)
   在 System.Transactions.TransactionStateAborted.EnterState(InternalTransaction tx)
   在 System.Transactions.TransactionStateActive.Rollback(InternalTransaction tx, Exception e)
   在 System.Transactions.EnlistableStates.Timeout(InternalTransaction tx)
   在 System.Transactions.Bucket.TimeoutTransactions()
   在 System.Transactions.BucketSet.TimeoutTransactions()
   在 System.Transactions.TransactionTable.ThreadTimer(Object state)
   在 System.Threading.TimerQueueTimer.CallCallbackInContext(Object state)
   在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   在 System.Threading.TimerQueueTimer.CallCallback()
   在 System.Threading.TimerQueueTimer.Fire()
   在 System.Threading.TimerQueue.FireNextTimers()
   在 System.Threading.TimerQueue.AppDomainTimerCallback()</StackTrace><ExceptionString>Npgsql.NpgsqlOperationInProgressException: A command is already in progress: insert into user_extra (sex, province, city, country, has_subscribed, subscribe_time) values('M', 'ABCD', 'EFG', 'XYZ', true, LOCALTIMESTAMP)
   在 Npgsql.NpgsqlConnector.StartUserAction(ConnectorState newState, NpgsqlCommand command)
   在 Npgsql.NpgsqlConnector.Rollback(Boolean async, CancellationToken cancellationToken)
   在 Npgsql.NpgsqlTransaction.&amp;lt;Rollback&amp;gt;d__21.MoveNext()
--- 引发异常的上一位置中堆栈跟踪的末尾 ---
   在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   在 Npgsql.NpgsqlTransaction.Rollback()
   在 Npgsql.NpgsqlTransaction.Dispose(Boolean disposing, Boolean doRollbackIfNeeded)
   在 Npgsql.NpgsqlTransaction.Dispose(Boolean disposing)
   在 System.Data.Common.DbTransaction.Dispose()
   在 Npgsql.VolatileResourceManager.Dispose()
   在 Npgsql.VolatileResourceManager.Rollback(Enlistment enlistment)
   在 System.Transactions.VolatileEnlistmentAborting.EnterState(InternalEnlistment enlistment)
   在 System.Transactions.VolatileEnlistmentActive.InternalAborted(InternalEnlistment enlistment)
   在 System.Transactions.TransactionStateAborted.EnterState(InternalTransaction tx)
   在 System.Transactions.TransactionStateActive.Rollback(InternalTransaction tx, Exception e)
   在 System.Transactions.EnlistableStates.Timeout(InternalTransaction tx)
   在 System.Transactions.Bucket.TimeoutTransactions()
   在 System.Transactions.BucketSet.TimeoutTransactions()
   在 System.Transactions.TransactionTable.ThreadTimer(Object state)
   在 System.Threading.TimerQueueTimer.CallCallbackInContext(Object state)
   在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   在 System.Threading.TimerQueueTimer.CallCallback()
   在 System.Threading.TimerQueueTimer.Fire()
   在 System.Threading.TimerQueue.FireNextTimers()
   在 System.Threading.TimerQueue.AppDomainTimerCallback()</ExceptionString></Exception></TraceRecord>
An unhandled exception of type 'Npgsql.NpgsqlOperationInProgressException' occurred in mscorlib.dll
A command is already in progress: insert into user_extra (sex, province, city, country, has_subscribed, subscribe_time) values('M', 'ABCD', 'EFG', 'XYZ', true, LOCALTIMESTAMP)

If I run this code on .NET Core 2.0 environment. I will receive similar crash information like this:

An unhandled exception of type 'Npgsql.NpgsqlOperationInProgressException' occurred in System.Private.CoreLib.dll
A command is already in progress: insert into user_extra (sex, province, city, country, has_subscribed, subscribe_time) values('M', 'ABCD', 'EFG', 'XYZ', true, LOCALTIMESTAMP)

But no stack trace will be printed on .NET Core 2.0 environment.

As you see, this is not normal .NET exception, it seems that issue occurs in the .NET's kernel, so I even can not catch the exception and make my program continue to work. So I call this Crash.

When this issue occurred, Visual Studio will show a window with The application is in break mode title, but no more helpful information.

Further technical details

Npgsql version: 3.2.3
PostgreSQL version: PostgreSQL 9.6 on CentOS7
Operating system: Windows10 with .NET framework 4.7 and .NET Core 2.0

Activity

  1. guogangj commented on Mar 10, 2018

    @guogangj
    Author

    After further research, I found it could be a transaction timeout problem. I am doing more tests on it and I will give feedback later.

  2. roji commented on Mar 10, 2018

    @roji
    Member

    That would make sense. TransactionScope's timeout is problematic, since it's a completely concurrent invocation of rollback that can happen at the same time as user operations. I'm not sure how ADO.NET provider are actually supposed to deal with this.

    Let me know what you find, you can easily disable the timeout via the TransactionScope's constructor.

  3. guogangj commented on Mar 11, 2018

    @guogangj
    Author

    Finally, I confirm this is a transaction timeout problem. The task will be completed successfully if I set the timeout value long enough. But I still think a normal exception should be catched in this situation, program crashing is dangerous and unrecoverable.

  4. roji commented on Mar 11, 2018

    @roji
    Member

    Thanks for confirming @guogangj.

    As you can see, Npgsql actually does throw a normal NpgsqlOperationInProgressException. As to why the exception isn't properly caught and your program crashes - I don't know but it's certainly not something special Npgsql is doing. I'll keep this issue and will try to find the time to run your repro and investigate (although I'm extremely busy at the moment).

    The workaround is simply to disable the timeout on the TransactionScope.

    Note: the actual discussion on better dealing with the concurrent rollback triggered by TransactionScope() is in #1611.

  5. roji commented on Jun 9, 2018

    @roji
    Member

    Closing as there doesn't seem to be anything actionable here, aside from the TransactionScope concurrent rollback-on-timeout behavior which is already covered by #1611.

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

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions