Repository navigation
Description
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
roji commentedon Oct 30, 2016
@realityexists, yes, that's the expected behavior in 3.1, because of #689.
To summarize, before 3.1 Npgsql used the PostgreSQL
statement_timeoutparameter to control timeouts.statement_timeoutisn'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_timeoutbehavior 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.
realityexists commentedon Oct 30, 2016
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_timeoutmyself. 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.
roji commentedon Oct 30, 2016
@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_timeoutafter 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.
realityexists commentedon Oct 30, 2016
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.
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 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.
roji commentedon Oct 31, 2016
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_timeoutyourself, keep in mind that you have to reset it back after the query - it's a session parameter that persists until changed. When Npgsql managedstatement_timeoutfor you, it would check if the timeout change is necessary on each command.I agree.
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.
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:
statement_timeoutcan be used to deal with this.To summarize, the solution here would be:
which means that a single NpgsqlCommand may produce multiple ReadyForQuerysa single NpgsqlCommand may produce multiple CommandComplete's, but always just one ReadyForQuery.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.
realityexists commentedon Oct 31, 2016
OK, that makes sense. Thanks a lot for re-opening this!
roji commentedon Dec 18, 2016
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.
7 remaining items
roji commentedon Sep 17, 2020
Duplicate of #3130realityexists commentedon Sep 17, 2020
Wow, fixed almost 4 years later! Thank you.
roji commentedon Sep 18, 2020
Better (really) late than never 🤣
roji commentedon Sep 22, 2020
Duplicate of #1567