Skip to content

Clean up and review exception behavior #330

Closed

Description

@roji

While working on the state refactoring in #326, I thought a little about how Npgsql happens exceptions and how they interact with the connector/connection state.

If any sort if error occurs (networking, server-reported), Npgsql wraps it in an NpgsqlException. It seems that it is currently impossible to know what the state of the connection is following an exception; the user has no means of knowing whether they can continue using the connection after an exception (they can after a server-reported exception, e.g. invalid SQL, but they can't after a networking exception).

What we probably need to do is to update the connector (and connection) state appropriately. A fatal exception (e.g. networking) should set the connection state to Broken, signaling to the user that they need to open and close if they wish to continue (this is described here, even if the ConnectionState.Broken is still marked as reserved for future use). This seems pretty straightforward to me, let me know if you see any issue.

One additional thing I'm less sure about, is the handling of ThreadAbortException in various places in the codebase - we attempt to cancel the query and close. Thread.Abort() in general is considered to be an extremely bad way of stopping user tasks (see this article, and also this stackoverflow discussions and especially Eric Lippert's answer).

The put it very simply, if some user does Thread.Abort() at the wrong moment, it's very easy to totally mess up Npgsql's internal state in a very bad way, since the ThreadAbortException can occur at any point in the code. So in general this kind of scenario isn't handled, especially by 3rd-party libraries, except for very specific scenarios.

I'm leaning towards removing special handling of Thread.Abort(), and allow regular exception handling to take place - change the connection state to Broken. We'd lose the automatic cancellation that currently happens when a thread is aborted during a query, but I think it's safer/healthier/cleaner to say that Thread.Abort() is simply not supported (since it pretty much can't be, in any guaranteed and meaningful way).

Can anyone with experience on this comment?

Activity

  1. self-assigned this
    on Sep 2, 2014
  2. added this to the milestone on Sep 2, 2014
  3. jbcooley commented on Sep 2, 2014

    @jbcooley
    Contributor

    I want to say that this came up in the context of IIS cancelling requests. I believe the connection pool was getting trashed when requests were cancelled. Of course it's been a long time, so I may be wrong on the details.

  4. roji commented on Sep 4, 2014

    @roji
    MemberAuthor

    Thanks for the comment @jbcooley.

    Looking at it some more:

    • We ourselves terminate the async notification thread using Thread.Abort(). I'm sure this is potentially dangerous; but in any case the plan is to reimplement async notifications without an entire thread per connection as described in Optimize implementation of Postgresql async notifications #270, so this will disappear.
    • It seems true that IIS does abort threads (long-standing ones, or automatic recycling every X hours). IMHO the question is whether the application is expected to actually work after a thread abort, or whether it's an abort that comes just before the app shuts down (or is reloaded). The way I understand things, there's absolutely no way an application can be expected to function properly after a ThreadAbortedException, simply because it can happen anywhere and screw up your state.
    • I'm a bit worried people might get used to the idea that they can cancel queries by aborting the thread. We support proper cancellation, of course, which should be used instead of Thread.Abort().
    • Finally, we of course have query timeout, both server-side and client-side. This already provides a clean and correct mechanism for ensuring we don't get stuck on a query (rather than having something exterior like IIS issue a Thread.Abort()).

    But I admit I don't know enough about IIS, it would be great to have an expert opinion here. I'm still heavily leaning towards removing special handling of ThreadAbortedException, but don't think we should do it before we get a clear picture.

  5. roji commented on Sep 12, 2014

    @roji
    MemberAuthor

    An unrelated question. I have a test failing on the build server because Npgsql generated an IOException and the test expected an NpgsqlException.

    I have no idea why this happened now, but there's a general question: should Npgsql always generate NpgsqlException, and wrap causes as inner exceptions? Personally I prefer the idea of always having NpgsqlExceptions, this way users can know by the exception type that it came from Npgsql. But this does not seem to be the behavior in SQL Server:

    This class is created whenever the .NET Framework Data Provider for SQL Server encounters an error generated from the server. (Client side errors are thrown as standard common language runtime exceptions.)

    It will also be more difficult to hunt down and wrap exceptions like IOExceptions. Easier to just let them bubble up to the user.

    Any thoughts/comments?

  6. Emill commented on Sep 12, 2014

    @Emill
    Contributor

    I also think it's better to separate database errors from things like network errors...

  7. franciscojunior commented on Sep 13, 2014

    @franciscojunior
    Member

    An unrelated question. I have a test failing on the build server because Npgsql generated an IOException and the test expected an NpgsqlException.

    This specific error is because it is trying to find the resources which contain the error message and it is not being able to be found. So it throws the IOException because it is being generated the the file reader.

    I have no idea why this happened now, but there's a general question: should Npgsql always generate NpgsqlException, and wrap causes as inner exceptions? Personally I prefer the idea of always having NpgsqlExceptions, this way users can know by the exception type that it came from Npgsql. But this does not seem to be the behavior in SQL Server:

    This class is created whenever the .NET Framework Data Provider for SQL Server encounters an error generated from the server. (Client side errors are thrown as standard common language runtime exceptions.)
    

    That documentation was exactly the inspiration for the current situation of NpgsqlException: All server and network related exceptions are wrapped with NpgsqlException and all other client side, like invalid argument, and others are thrown as standard common language.

  8. roji commented on Sep 14, 2014

    @roji
    MemberAuthor

    This specific error is because it is trying to find the resources which contain the error message and it is not being able to be found. So it throws the IOException because it is being generated the the file reader.

    Sorry, I think I posted the link to the wrong failing test. This is the right one. I will investigate what's going on (only happens on build server, not here). The stack trace is:

    Test(s) failed. An unexpected exception type was thrown
    Expected: Npgsql.NpgsqlException
     but was: System.IO.IOException : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
       at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
       at System.IO.BufferedStream.ReadByte()
       at Npgsql.NpgsqlConnector.<ProcessBackendResponses>d__0.MoveNext() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlConnector.cs:line 615
       at Npgsql.NpgsqlConnector.ProcessAndDiscardBackendResponses() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlConnector.cs:line 540
       at Npgsql.NpgsqlConnector.Open() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlConnector.cs:line 276
       at Npgsql.NpgsqlConnection.Open() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlConnection.cs:line 656
       at NpgsqlTests.CommandTests.ConnectionStringWithInvalidParameterValue()
    

    But regardless, @franciscojunior, aren't network-related exceptions a cilent-side issue, and therefore should not be wrapped by NpgsqlException? According to my understanding of the SQL Server spec only errors returned from the backend (i.e. a backend ErrorResponse message) should be an Sql/NpgsqlException. What do you think?

  9. franciscojunior commented on Sep 15, 2014

    @franciscojunior
    Member

    Sorry, I think I posted the link to the wrong failing test. This is the right one. I will investigate what's going on (only happens on build server, not here). The stack trace is:

    It seems the link is still pointing to the resource file missing exception :)

    The stack trace is:

    Test(s) failed. An unexpected exception type was thrown
    Expected: Npgsql.NpgsqlException
    but was: System.IO.IOException : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
    at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
    at System.IO.BufferedStream.ReadByte()
    at Npgsql.NpgsqlConnector.d__0.MoveNext() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlConnector.cs:line 615
    at Npgsql.NpgsqlConnector.ProcessAndDiscardBackendResponses() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlConnector.cs:line 540
    at Npgsql.NpgsqlConnector.Open() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlConnector.cs:line 276
    at Npgsql.NpgsqlConnection.Open() in c:\dev\TeamCity\buildAgent\work\c548594815738d27\Npgsql\Npgsql\NpgsqlConnection.cs:line 656
    at NpgsqlTests.CommandTests.ConnectionStringWithInvalidParameterValue()

    This is a case where we aren't honoring the idea of wrapping the server side exception with NpgsqlException. This is an error in Npgsql. It should be wrapping this IOException in a NpgsqlException.

    But regardless, @franciscojunior, aren't network-related exceptions a cilent-side issue, and therefore should not be wrapped by NpgsqlException? According to my understanding of the SQL Server spec only errors returned from the backend (i.e. a backend ErrorResponse message) should be an Sql/NpgsqlException. What do you think?

    Hmmmm, my understanding was that network related exceptions were server side related. But I see what you are saying. As the network exception is derived from a client side interaction, instead of a server processing, it should be thrown to the client as the original exception. And re reading sqlException and SqlCommand.ExecuteReader() method descriptions, I think you are right and the current Npgsql approach of wrapping all network and server related exceptions inside NpgsqlException is not ideal.

    I hope it is not too late to change this assumption. As 3.0 is introducing a lot of potential breakage, I think this is the right time to correct this :)

    +1 for changing this.

    So, in this new interpretation, the error above is not an error. It is the desired behavior and the test should be changed to reflect that.

  10. roji commented on Mar 29, 2015

    @roji
    MemberAuthor

    AFAIK all exception-related issues are solved. There's still special thread-abort exception handling in the connection pool, we'll look at this in 3.1 when the rest of the connection pool will take place.

  11. modified the milestones: , 3.0-beta1 on Mar 30, 2015
  12. modified the milestones: 3.0-beta1, on Aug 7, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions