Skip to content

Some exceptions are thrown from NpgsqlDataReader.Read() instead of NpgsqlCommand.ExecuteReader() #400

Closed

Description

@realityexists

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

  1. roji commented on Feb 19, 2015

    @roji
    Member

    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?

  2. added this to the milestone on Feb 19, 2015
  3. self-assigned this
    on Feb 19, 2015
  4. realityexists commented on Feb 19, 2015

    @realityexists
    Author

    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!

  5. realityexists commented on Mar 10, 2015

    @realityexists
    Author

    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.

  6. modified the milestones: , 3.0-beta1 on Mar 30, 2015
  7. modified the milestones: 3.0-beta1, on May 24, 2015
  8. modified the milestones: , on Jun 26, 2015
  9. 3 remaining items

  10. realityexists commented on Oct 19, 2015

    @realityexists
    Author

    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.

  11. added a commit that references this issue on Oct 23, 2015
    187c648
  12. modified the milestones: 3.0.4, on Oct 23, 2015
  13. roji commented on Oct 23, 2015

    @roji
    Member

    @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.

  14. changed the title [-]Timeout exception occurs in NpgsqlDataReader.Read() instead of NpgsqlCommand.ExecuteReader()[/-] [+]Some exceptions are thrown from NpgsqlDataReader.Read() instead of NpgsqlCommand.ExecuteReader()[/+] on Oct 23, 2015
  15. realityexists commented on Oct 23, 2015

    @realityexists
    Author

    Great! Thank you.

  16. RafaelSalguero commented on Oct 26, 2015

    @RafaelSalguero

    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

  17. roji commented on Oct 27, 2015

    @roji
    Member

    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.

  18. JuFrolov commented on Feb 15, 2016

    @JuFrolov

    Hi,
    NpgsqlDataReader is successfully returned but the NpgsqlException 57014
    I have the 3.0.5 Lastest stable NuGet.
    Fix had been made?
    ST:

    at Npgsql.NpgsqlConnector.DoReadSingleMessage(DataRowLoadingMode dataRowLoadingMode, Boolean returnNullForAsyncMessage, Boolean isPrependedMessage)
    at Npgsql.NpgsqlConnector.ReadSingleMessage(DataRowLoadingMode dataRowLoadingMode, Boolean returnNullForAsyncMessage)
    at Npgsql.NpgsqlDataReader.ReadMessage()
    at Npgsql.NpgsqlDataReader.Init()
    at Npgsql.NpgsqlCommand.Execute(CommandBehavior behavior)
    at Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal(CommandBehavior behavior)
    at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
    at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed)
    at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
    at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

  19. roji commented on Apr 1, 2016

    @roji
    Member

    @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?

  20. roji commented on Apr 17, 2016

    @roji
    Member

    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.

  21. 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