Repository navigation
Description
When a query times out I sometimes want to re-try the same query with a longer timeout. I have a "ExecuteReaderWithRetry" method in my application which encapsulates this logic (catching the timeout exception and rolling back to a savepoint) and returns an NpgsqlReader to the caller. The idea is that the caller should then be able to use this reader normally, as if they got it from NgpsqlCommand.ExecuteReader().
This worked fine up Npgsql 2.0.14.3. From 2.1.0 onwards it fails, because the timeout exception is thrown from the NpgsqlReader.Read() method, which is called by user code outside of the savepoint. I tried accessing NpgsqlReader.HasRows to force the timeout to happen within the savepoint (if it was going to happen), but this is only a partial workaround: it works if the query takes too long to return the first row, but not if it takes too long to return subsequent rows. In 2.0.14, a reader seemed to be returned only once the first row was ready and after that I could keep reading the rest of the result set - the timeout no longer mattered. This is the behaviour I want. Could you enable this somehow in 2.2.1+, please?
Simplified code that reproduces the problem:
class Program
{
static void Main(string[] args)
{
var connectionString = "<your connection string>";
// This works fine with Npgsql 2.0.14.3, but fails with a timeout in NpgsqlReader.Read() with Npgsql 2.2.1:
/*
Unhandled Exception: Npgsql.NpgsqlException: ERROR: 57014: canceling statement due to statement timeout
at Npgsql.NpgsqlState.<ProcessBackendResponses>d__0.MoveNext() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlState.BackendResponse.cs:line 310
at Npgsql.ForwardsOnlyDataReader.GetNextResponseObject(Boolean cleanup) in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlDataReader.cs:line 1158
at Npgsql.ForwardsOnlyDataReader.GetNextRow(Boolean clearPending) in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlDataReader.cs:line 1259
at Npgsql.ForwardsOnlyDataReader.Read() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlDataReader.cs:line 1403
at NpgsqlTest.Program.Main(String[] args) in NpgsqlTest\Program.cs:line 24
*/
var conn = new NpgsqlConnection(connectionString);
conn.Open();
var transaction = conn.BeginTransaction();
// const string commandText = "SELECT pg_sleep(3)"; // This works with the HasRows workaround (see below)
const string commandText = "SELECT pg_sleep(2) FROM generate_series(1, 3)"; // This still doesn't
var reader = ExecuteReaderWithRetry(conn, transaction, commandText);
Console.WriteLine("Got a reader, reading from it...");
while (reader.Read())
{
}
Console.WriteLine("Done");
}
private static NpgsqlDataReader ExecuteReaderWithRetry(NpgsqlConnection conn, NpgsqlTransaction transaction,
string commandText)
{
transaction.Save("TestSavePoint");
var command = new NpgsqlCommand(commandText, conn);
command.CommandTimeout = 1;
Console.WriteLine("Trying with timeout = {0} seconds", command.CommandTimeout);
NpgsqlDataReader reader;
try
{
reader = command.ExecuteReader();
if (reader.HasRows)
{
// Calling HasRows provides a PARTIAL workaround - the first Read() will not time out. Subsequent
// calls to Read() still may, however.
}
}
catch (NpgsqlException ex)
{
if (!ex.Message.Contains("A timeout has occured")
&& !ex.Message.Contains("canceling statement due to statement timeout"))
{
throw;
}
// Roll back to a savepoint
Console.WriteLine("Command timed out (as expected), rolling back to savepoint and trying again");
transaction.Rollback("TestSavePoint");
command.CommandTimeout = 5;
Console.WriteLine("Trying again with timeout = {0} seconds", command.CommandTimeout);
reader = command.ExecuteReader();
if (reader.HasRows)
{
// Shouldn't time out this time.
}
}
return reader;
}
}
Activity
roji commentedon Feb 19, 2015
I just came across this issue, sorry for not commenting earlier, it must have slipped through the cracks.
I've done a lot of rewriting around how ExecuteReader() happens for our next major version, v3.0. In the last implementation in master, unprepared commands will work in the way you want, since ExecuteQuery() must wait for certain messages to arrive from the server (e.g. row description). Prepared commands, however, already have what they need, and so ExecuteReader() returns immediately.
Regardless of your specific use case, it makes sense to me to have ExecuteReader() wait even for prepared commands (for coherent behavior), I'll look at it in for v3.0. This should solve your issue.
And out of curiosity, can you please explain the motivation behind your retry-with-longer-timeout technique? Why not simply run with the longer timeout in the first place?
realityexists commentedon Feb 19, 2015
Good question! I've run into some bizarre cases where a query may initially time out no matter how long I wait, but the second time it runs in a reasonable time. Usually it runs OK the first time and this isn't reliably reproducible, so clearly something weird is going on. Perhaps Postgres creates a bad plan initially and then learns from its mistake!
realityexists commentedon Mar 10, 2015
Is there a fix, or at least workaround, for this that can be applied to version 2.2? We're still using 2.0.14.3 due to this issue, but are now also running into bug 252. I tried to backport Emill's fix for that to 2.0.14.3, but that seems like quite an uphill battle. So maybe fixing this and upgrading would be the easier path.
3 remaining items
realityexists commentedon Oct 19, 2015
Any chance of this being fixed soon? We're still running into issue #252 and would love to upgrade our ancient version of Npgsql (2.0.14.3), but can't until this is fixed.
Throw NpgsqlExceptions earlier
roji commentedon Oct 23, 2015
@realityexists, I finally got around to fixing this. Version 3.0.4 (which will be published in the next few days) will contain a fix for this.
[-]Timeout exception occurs in NpgsqlDataReader.Read() instead of NpgsqlCommand.ExecuteReader()[/-][+]Some exceptions are thrown from NpgsqlDataReader.Read() instead of NpgsqlCommand.ExecuteReader()[/+]realityexists commentedon Oct 23, 2015
Great! Thank you.
RafaelSalguero commentedon Oct 26, 2015
We have the same problem, according to the Console output the NpgsqlDataReader is successfully returned but the NpgsqlException 57014 is thrown. The fix is already available? I have the 3.0.3 Lastest stable NuGet. Should I download the 3.1.0 alpha-1 or wait for the 3.0.4. nuget? Thanks
roji commentedon Oct 27, 2015
The fix has been committed but not yet released. You should wait for 3.0.4 which should be released very soon, or download the latest 3.0.4 beta from the unstable feed.
JuFrolov commentedon Feb 15, 2016
Hi,
NpgsqlDataReader is successfully returned but the NpgsqlException 57014
I have the 3.0.5 Lastest stable NuGet.
Fix had been made?
ST:
roji commentedon Apr 1, 2016
@JuFrolov, what exactly is the problem you're reporting? Error 57014 means that your query was cancelled - do you have other threads performing cancellations or something?
roji commentedon Apr 17, 2016
Note to everyone: this fix applies only to errors raised by the first statement - a command may have multiple statements. If a later statement raises an error it will only be caught when its resultset is traversed.