Skip to content

Connection is closed after command timeout #1344

Closed as duplicate
Closed as duplicate

Description

@realityexists

I'm trying to get the code from #400 working again in Npgsql 3 (dev branch) and it now fails really badly: after the first timeout the connection is closed, so I cannot rollback to the savepoint and continue! Note that I haven't modified the connection timeout - it's still the default 15 seconds (though I don't think it would even matter once the connection is open).

Code:

private static void TestTimeoutAndRetryIssue(NpgsqlConnection connection)
{
    using (var transaction = connection.BeginTransaction())
    {
        using (var command = new NpgsqlCommand("SELECT :value FROM pg_sleep(:seconds)", connection))
        {
            command.Parameters.AddWithValue(":value", "Initial");
            command.Parameters.AddWithValue(":seconds", 5);

            var result = ExecuteScalarWithRetry(transaction, command, 5, 1);
        }
    }
}

private static object ExecuteScalarWithRetry(NpgsqlTransaction transaction, NpgsqlCommand command, int delaySec, int initialTimeoutSec)
{
    transaction.Save("ExecuteScalarWithRetry");

    command.CommandTimeout = initialTimeoutSec;
    command.Parameters[":value"].Value = "Attempt 1";

    try
    {
        return command.ExecuteScalar();
    }
    catch (NpgsqlException ex)
    {
        Console.WriteLine("Exception in ExecuteScalarWithRetry: " + ex);
        Console.WriteLine("Connection state = " + command.Connection.State); // Closed!
    }
}

Exception:

Npgsql.NpgsqlException (0x80004005): Exception while reading from stream ---> System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at Npgsql.ReadBuffer.Ensure(Int32 count, Boolean dontBreakOnTimeouts) in E:\Source\npgsql\src\Npgsql\ReadBuffer.cs:line 115
at Npgsql.ReadBuffer.Ensure(Int32 count, Boolean dontBreakOnTimeouts) in E:\Source\npgsql\src\Npgsql\ReadBuffer.cs:line 133
at Npgsql.NpgsqlConnector.DoReadMessage(DataRowLoadingMode dataRowLoadingMode, Boolean isPrependedMessage) in E:\Source\npgsql\src\Npgsql\NpgsqlConnector.cs:line 884
at Npgsql.NpgsqlConnector.ReadMessageWithPrepended(DataRowLoadingMode dataRowLoadingMode) in E:\Source\npgsql\src\Npgsql\NpgsqlConnector.cs:line 856
at Npgsql.NpgsqlConnector.ReadMessage(DataRowLoadingMode dataRowLoadingMode) in E:\Source\npgsql\src\Npgsql\NpgsqlConnector.cs:line 836
at Npgsql.NpgsqlConnector.ReadExpectingT in E:\Source\npgsql\src\Npgsql\NpgsqlConnector.cs:line 1111
at Npgsql.NpgsqlDataReader.NextResultInternal() in E:\Source\npgsql\src\Npgsql\NpgsqlDataReader.cs:line 409
at Npgsql.NpgsqlDataReader.NextResult() in E:\Source\npgsql\src\Npgsql\NpgsqlDataReader.cs:line 320
at Npgsql.NpgsqlCommand.d__81.MoveNext() in E:\Source\npgsql\src\Npgsql\NpgsqlCommand.cs:line 769
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at Npgsql.NpgsqlCommand.<ExecuteScalar>d__98.MoveNext() in E:\Source\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1066 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Npgsql.NpgsqlCommand.ExecuteScalar() in E:\Source\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1041
at NpgsqlTest.Program.ExecuteScalarWithRetry(NpgsqlTransaction transaction, NpgsqlCommand command, Int32 delaySec, Int32 initialTimeoutSec)

Activity

  1. roji commented on Oct 30, 2016

    @roji
    Member

    @realityexists, yes, that's the expected behavior in 3.1, because of #689.

    To summarize, before 3.1 Npgsql used the PostgreSQL statement_timeout parameter to control timeouts. statement_timeout isn't really suitable for this - PostgreSQL counts the total time the statement is in progress, so if the client doesn't read query results fast enough the timeout may be triggered. Also, in case of an actual network connection drop, this mechanism doesn't work at all.

    Because of this, 3.1 reimplemented command timeouts as socket timeouts, which are 100% reliable and represent network read timeout, which is simpler and makes more sense. Unfortunately, if a socket timeout occurs Npgsql loses protocol sync with the server, and so the connection is broken.

    This isn't an ideal situation, but I'm not aware of a better solution at the moment. On the other hand, if you really want the previous statement_timeout behavior you can easily set it yourself.

    I'm going to close this issue because that's the current expected behavior, but I'd be happy to discuss it (and alternatives) so feel free to continue posting here.

  2. realityexists commented on Oct 30, 2016

    @realityexists
    Author

    Well... this is really a serious problem for our application. It starts a transaction that can sometimes run for hours with many commands in it. We rely on transaction savepoints to recover from intermittent timeouts, which unfortunately do occur relatively frequently. This behaviour means that if any one of the thousands of commands in the transaction times out all the transaction's work is lost, despite the savepoints.

    More generally, I don't think a broken connection is what the user would expect after a timeout exception that's caught and handled.

    Yes, I could set statement_timeout myself. I tested it briefly and it seems to work, though it has to be done in a separate command (just prepending "SET statement_timeout = 12345;" to CommandText seems to have no effect). This is far from ideal, though, because not only do we have to change all 115 places in the code that set a CommandTimeout, but also make sure it's not added later. I can't even sub-class NpgsqlCommand to inject this behaviour, because it's sealed.

    As I understood from #689, you've implemented the same behaviour as SqlClient (CommandTimeout is the cumulative network timeout for all reads), which is good - this is what I'd expect CommandTimeout to do. Why does Npgsql lose sync with the server after a socket timeout, though? How does SqlClient solve this problem? I don't have a SQL Server handy to test with right now, but I don't think it breaks the connection on a timeout.

  3. roji commented on Oct 30, 2016

    @roji
    Member

    @realityexists, I understand your issue. The current timeout situation isn't ideal, it's just that for the moment there doesn't seem to be a better situation.

    Out of curiosity, do you know why you're getting intermittent timeouts? Are these network-related, PostgreSQL deadlocks? In general, an application which anticipates a timeout and retries the statement is a complicated (and dangerous) technique for avoiding the root of the issue.

    But I'm probably not telling you anything new, and of course you probably have good reasons for doing what you're doing. One suggestion would be to set statement_timeout after opening the connection (rather than before executing the command), this may simplify things if you already centralize connection creation (for connection string reasons, for example). I'm not sure exactly why NpgsqlCommand is sealed (although SqlCommand is sealed as well).

    Note that for the moment, network timeouts are not cumulative. They clearly should be, and this is tracked by #1041. Regarding why sync is lost... When a socket timeout occurs, an exception is thrown to the user. At this point the query results are still pending, while control has been transferred back to the user. The user may execute a new statement, and Npgsql has to internally track the state of things and be aware that the previous statement's results must be consumed before the new statement's results can be read (there can actually be several previous queries that need to be consumed). Another issue is that if the first query is really taking too long (e.g. deadlock or incredibly intensive to execute), the next query will timeout as well because the first one still has to complete. This could probably be mitigated by sending a cancellation when a timeout occurs.

    I think it's definitely possible to solve the problems above, but it's definitely not an easy task and there have been more pressing matters recently. Also, I think of the current socket timeout mechanism primarily as a way to deal with network issues - where the connection is lost - rather than with commands which take too long to execute on the server side. Viewed this way it makes some sense for the connection to be broken, although I agree it may make sense to deal with the latter scenario as well.

    I can confirm that SQL Server doesn't break the connection on timeout. I have no idea what happens there - I know very little about the protocol and I/O handling.

    To sum up, I'm definitely open to suggestions and ideas on how to improve timeouts.

  4. realityexists commented on Oct 30, 2016

    @realityexists
    Author

    Thanks for the detailed explanation.

    Our timeouts are not network related. They're definitely due to the query taking too long on the server (so a server-side timeout worked well for us). Sometimes it's just due to the load on the server at the time, so it makes sense to re-try. Other times something really weird is going on inside Postgres and we've just never been able to track down why a query that usually returns in 100 ms sometimes takes 5 minutes.

    Due to the above I'd want to set a different statement_timeout for each command. Most commands are OK with the default 20 or 30 seconds, but one may need as long as an hour. Obviously I wouldn't want to set the timeout to an hour for every command, because if something is really blocked/deadlocked on the server I'd want them to fail faster than that. So I think setting statement_timeout will work, but it will take quite a bit of work on my side to change the code to set it everywhere.

    Another issue is that if the first query is really taking too long (e.g. deadlock or incredibly intensive to execute), the next query will timeout as well because the first one still has to complete. This could probably be mitigated by sending a cancellation when a timeout occurs.

    I think it definitely makes sense to cancel the query when a timeout occurs. After all, if the Execute* method throws an exception there is no way the user can read the results. If the statement modified data the user would probably also have to roll back to a savepoint to get the DB to a known state (which is what we do).

    When a socket timeout occurs, an exception is thrown to the user. At this point the query results are still pending, while control has been transferred back to the user. The user may execute a new statement, and Npgsql has to internally track the state of things and be aware that the previous statement's results must be consumed before the new statement's results can be read

    I think I see what you mean. Even if the query was cancelled, some results may still arrive afterwards? Is there a way to detect the end of the results for the cancelled query? If so, Npgsql could block until it receives them. That is, it could catch the socket timeout exception, send a cancellation to the server and wait for any remaining results for this query from the server before throwing a timeout exception to the user. This way it wouldn't have to keep track of any special state for the next query.

  5. added this to the 3.2 milestone on Oct 31, 2016
  6. self-assigned this
    on Oct 31, 2016
  7. roji commented on Oct 31, 2016

    @roji
    Member

    Our timeouts are not network related. They're definitely due to the query taking too long on the server (so a server-side timeout worked well for us). Sometimes it's just due to the load on the server at the time, so it makes sense to re-try. Other times something really weird is going on inside Postgres and we've just never been able to track down why a query that usually returns in 100 ms sometimes takes 5 minutes.

    Wow, I can feel your pain. For cases where the server is overloaded, it may make sense to set timeout to a high value (or even disable timeouts altogether) - if the server is loaded you may as well wait for the query to complete, no matter how long it takes, rather than cancelling and rerunning it (which offers no advantage and actually repeats a lot of work).

    However, for a query to take 5 minutes is probably something else. One frequent cause for this is some other connection holding a long-lived transaction which already updated a row you're trying to update. PostgreSQL locks rows when they are modified in a transaction, so your 5-minute query is possibly waiting for the other transaction to complete. This would also explains why you can't reproduce it - it's a true concurrency issue. Long-lived transactions are in general a big problem, especially if you have many of them touching the same data.

    While I'd really recommend attempting to solve the root cause, I do appreciate that it can be hard to track down issues like this, and hacky workarounds like timeout+retry are sometimes necessary.

    If you do end up setting statement_timeout yourself, keep in mind that you have to reset it back after the query - it's a session parameter that persists until changed. When Npgsql managed statement_timeout for you, it would check if the timeout change is necessary on each command.

    I think it definitely makes sense to cancel the query when a timeout occurs. After all, if the Execute* method throws an exception there is no way the user can read the results. If the statement modified data the user would probably also have to roll back to a savepoint to get the DB to a known state (which is what we do).

    I agree.

    When a socket timeout occurs, an exception is thrown to the user. At this point the query results are still pending, while control has been transferred back to the user. The user may execute a new statement, and Npgsql has to internally track the state of things and be aware that the previous statement's results must be consumed before the new statement's results can be read

    I think I see what you mean. Even if the query was cancelled, some results may still arrive afterwards? Is there a way to detect the end of the results for the cancelled query?

    Yes, query cancellation is a best-effort asynchronous operation, which can cancel the current query at any point in time (or even not at all), so Npgsql must be prepared to consume any results from the cancelled query. Detect the end of the results of the cancelled query isn't hard - every executed command is ultimately terminated by a Sync message, which produces a ReadyForQuery response which signals the end of the query. We'd have to track how many cancelled queries are still in-flight, and read that many ReadyForQuery responses. There are some complications but it's doable.

    If so, Npgsql could block until it receives them. That is, it could catch the socket timeout exception, send a cancellation to the server and wait for any remaining results for this query from the server before throwing a timeout exception to the user. This way it wouldn't have to keep track of any special state for the next query.

    Unfortunately that isn't possible. In case of an actual network problem, this would make Npgsql block forever on the remaining results, defeating the whole purpose of the timeout. Whatever we do, an exception must be raised when the timeout occurs.

    The larger issue here is that there are two very different scenarios being handled via the same timeout concept:

    1. Network issue, dropped connection. If this occurs, it's possible that nothing will ever be received from the socket. Sending a cancellation has no effect (network isn't working). Socket timeouts are the only way to deal with this.
    2. Query taking too long or deadlocking. In this case cancellation works well. statement_timeout can be used to deal with this.

    To summarize, the solution here would be:

    • When a socket timeout occurs, keep track of how many ReadyForQuerys are pending on the connector, send a PostgreSQL cancellation and throw an exception. Note the Simple query optimization introduced in 3.2, which means that a single NpgsqlCommand may produce multiple ReadyForQuerys a single NpgsqlCommand may produce multiple CommandComplete's, but always just one ReadyForQuery.
    • When we execute a new command, we first check whether ReadyForQuerys are pending, and if so, we attempt to consume them before (or after?) sending the new query. This may timeout again (e.g. ongoing network issue).

    I'm not sure I'm going to have time to implement this in the very near future, there are many other things going on at the moment. But I'll make an effort.

  8. reopened this on Oct 31, 2016
  9. realityexists commented on Oct 31, 2016

    @realityexists
    Author

    OK, that makes sense. Thanks a lot for re-opening this!

  10. roji commented on Dec 18, 2016

    @roji
    Member

    Am going to move this to 3.3, this is definitely not trivial and I don't want to hold up 3.2 because of it.

  11. added this to the milestone on Dec 18, 2016
  12. 7 remaining items

  13. modified the milestones: 4.1, 5.0 on Aug 26, 2019
  14. roji commented on Sep 17, 2020

    @roji
    Member

    Duplicate of #3130

  15. removed this from the 5.0 milestone on Sep 17, 2020
  16. removed their assignment
    on Sep 17, 2020
  17. realityexists commented on Sep 17, 2020

    @realityexists
    Author

    Wow, fixed almost 4 years later! Thank you.

  18. roji commented on Sep 18, 2020

    @roji
    Member

    Better (really) late than never 🤣

  19. roji commented on Sep 22, 2020

    @roji
    Member

    Duplicate of #1567

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