You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Design ideas for proper thread-safe shutdown procedure #1162
You need a complex CancellationTokenSource-like structure. Constructed out of 2 CancellationTokenSources. I'd call it a ShutdownSignalSource or so.
The struct would expose 3 CancellationTokens, one representing "graceful" shutdown, one representing "abrupt" shutdown and one is a linked token which would signal when either of them are signalled.
The idea is that operations that should stop gracefully and wait for a time (till a configurable timeout with sane defaults) should listen on the graceful token, and the "wait for shutdown" itself should listen on the abrupt token.
When user requests a close, send a graceful signal.
When a socket error or timeout occurs, send the abrupt signal.
When the abrupt signal is sent, both sub-tokens should become signaled.
And in case a timeout or socket error occurs during a graceful shutdown, the complex token should support an Escalate method that would signal the Abrupt token which would change the shutdown type to abrupt.
As for the open and close itself they should be protected with a dedicated semaphore of 1 slot to support both sync and async flows.
In the case of a long-lived instance of NpgsqlConnection, if an abrupt shutdown happens in the background, the connection should become in the "broken" state and no action should be possible on it except to Dispose / Close.
I got these ideas when implementing a custom binary protocol client and it took me a very long while to get this right. So I hope that helps.
When I get some free time, I'll try my hand at a pull request implementing this.
changed the title [-]Design ideas for proper thread-safe shutdown procedure for 3.2[/-][+]Design ideas for proper thread-safe shutdown procedure[/+]on Jun 13, 2016
Hi @rwasef1830, I assume this is a proposal for properly resolving #1151 (and the other close-related sync issues detailed there). Thanks for your detailed thoughts on this! @MarkusSintonen, you may find this discussion interesting.
First, in case you're not aware Npgsql already manages 2 SemaphoreSlims, one for user actions and one for keepalives. When a user action starts (e.g. ExecuteReader), the user action semaphore is taken (an "Operation is already in progress" is thrown if the semaphore is already taken), and then the keepalive semaphore is busy. This makes sure we don't start a user action while a keepalive is in progress. All operations using the connection are supposed to go through this mechanism, ensuring that operations never run concurrently and that users get clean exceptions (as opposed to undefined behavior).
One current problem is that open and close do not take these semaphores, which is why @MarkusSintonen ran into a race condition if close happens just as a keepalive is in progress. This is tracked by #1127. My current direction to fix this in 3.2 is simply to make sure the semaphores are properly taken in close and open. Close is a bit tricky though: if a user operation or keepalive is in progress while Close is called, we want an abrupt shutdown (this isn't the behavior in 3.1, which instead waits for the operation to complete). However, making this work doesn't seem too hard - it's just too big a change for a patch-level 3.1 release.
Now regarding some of your specific comments:
You need a complex CancellationTokenSource-like structure. Constructed out of 2 CancellationTokenSources. I'd call it a ShutdownSignalSource or so.
The struct would expose 3 CancellationTokens, one representing "graceful" shutdown, one representing "abrupt" shutdown and one is a linked token which would signal when either of them are signalled.
I assume you're proposing to use the cancellation tokens just as a way to trigger the cancellation code, right? I mean, all this logic has to happen for synchronous operations which don't support cancellation tokens directly in any way... In that case, I'm not sure I see the usefulness of cancellation tokens vs. simply directly calling methods that perform the shutdown logic. Note that NpgsqlConnector already has a method Break() which is called whenever the connection is no longer usable (e.g. timeout). This method is very similar to your concept of an abrupt shutdown.
And in case a timeout or socket error occurs during a graceful shutdown, the complex token should support an Escalate method that would signal the Abrupt token which would change the shutdown type to abrupt.
To be honest, if the user requests a Close while one of their operations is still in progress, I don't even think we should wait for the operation to end on its own (graceful shutdown). In other words if an operation is in progress, it seems to me that a Close should be abrupt. The user is in control and chooses when to Close, and they can also decide to implement a timeout themselves if they so desire. Note that if a keepalive is in progress it does make sense to wait a bit, since keepalives aren't a user-triggered operation and are typically very short too.
As for the open and close itself they should be protected with a dedicated semaphore of 1 slot to support both sync and async flows.
Yep, I agree as I said above. The semaphore (or rather the two semaphores) already exist and are used, just not for open and close.
In the case of a long-lived instance of NpgsqlConnection, if an abrupt shutdown happens in the background, the connection should become in the "broken" state and no action should be possible on it except to Dispose / Close.
This is already the case, it happens when the Break() method is called.
When I get some free time, I'll try my hand at a pull request implementing this.
Thanks for offering to help with this, but it would be better to fully lock the design down in discussion before starting work. Note that I also have some WIP on this in a branch.
Hey @roji,
Hmmm, my model was based on a design I used for a completely async bidirectional packet-based binary protocol. I guess I didn't properly consider sync operations. I have to admit I am not familiar with the internal design of the NpgsqlConnection :-). I was just throwing out ideas to raise some insights.
I assume you're proposing to use the cancellation tokens just as a way to trigger the cancellation code, right? I mean, all this logic has to happen for synchronous operations which don't support cancellation tokens directly in any way...
The structure I proposed would be internal, not exposed to the users. It would be used for coordinating the internal components and dependencies of the connection itself, not passed from outside by the user. I favored basing it on CancellationToken because internally it handles the tricky lock-free multi-threading / read/write-fencing stuff so I don't have to worry about it.
In that case, I'm not sure I see the usefulness of cancellation tokens vs. simply directly calling methods that perform the shutdown logic.
In addition, it can be exposed to consumers of the connection (if there were any events or callbacks) to give them a chance to participate in the coordinated shutdown and it can be passed to any "injected" dependencies of the connection to link them easily into the shutdown process without strong coupling to the core connection code. (see HttpContext.RequestAborted for a similar idea used in ASP.net Core RC2).
To be honest, if the user requests a Close while one of their operations is still in progress, I don't even think we should wait for the operation to end on its own (graceful shutdown). In other words if an operation is in progress, it seems to me that a Close should be abrupt. The user is in control and chooses when to Close, and they can also decide to implement a timeout themselves if they so desire. Note that if a keepalive is in progress it does make sense to wait a bit, since keepalives aren't a user-triggered operation and are typically very short too.
If there are no possible background received commands or notifications from Postgresql, then Close should just immediately close the Socket and background tasks should be robust against that possibility, logging if this happened unexpectedly, or suppressing the warnings if the loss was due to the user calling Close.
I have to admit that I'm not really familiar with all features of Postgresql :-), learning as I go.
Thanks for offering to help with this, but it would be better to fully lock the design down in discussion before starting work. Note that I also have some WIP on this in a branch.
Well, I hope my idea helps in any way or leads to a more robust implementation. I struggled on such a task for weeks a few months ago :-).
Hi @roji and @rwasef1830,
I also think that the design using CancellationTokens is too heavy weight solution here since the NpgsqlConnector is fairly synchronous in nature (except that keep alive).
I would propose that there would by just a single (volatile) field inside NpgsqlConnector that would indicate if connector actions should be cancelled because connector is closing. This field would be checked by a method (CheckClosingState) that would throw an internal exception e.g. ConnectorClosingException if closing/cancelling is indicated. This method would be called inside relevant methods e.g. in PerformKeepAlive-SkipUntil and the possible ConnectorClosingException would be properly handled so that the operation is gracefully cancelled.
Using this mechanism the Close/Break would first set this closing state field and after this wait for the semaphore to be released. This waiting should be short since the currently running operation e.g. keep alive would be cancelled almost immediately. After the semaphore has been released all the resources are disposed. This would still need some little extra to make sure that the keep alive timer thread would not fire up and use the disposing resources while Close is running.
@MarkusSintonen no problem, your thoughts are definitely relevant!
In addition, it can be exposed to consumers of the connection (if there were any events or callbacks) to give them a chance to participate in the coordinated shutdown and it can be passed to any "injected" dependencies of the connection to link them easily into the shutdown process without strong coupling to the core connection code. (see HttpContext.RequestAborted for a similar idea used in ASP.net Core RC2).
Well, NpgsqlConnection already has the ADO.NET standard StateChange event which gets fired when the connection state changes, i.e. on open/close. This is the standard way to get updates on what's happening with the connection in a weakly-coupled way.
If there are no possible background received commands or notifications from Postgresql, then Close should just immediately close the Socket and background tasks should be robust against that possibility, logging if this happened unexpectedly, or suppressing the warnings if the loss was due to the user calling Close.
Aside from keepalives, everything that happens in Npgsql is user-initiated: the user starts a query and reads the results, etc. So I agree with what you're saying, with one exception: closing an idle connection should first send the PostgreSQL Terminate message. This lets PostgreSQL know about the connection (rather than an abrupt socket close), which is a good thing - otherwise PostgreSQL emits an error in its logs. So I see close as having two paths, a bit how you first described things: if the connection is idle Terminate is sent, otherwise the socket is abruptly closed. Also we need to remember pooling: closing an idle pooled connection needs to return it to the pool, whereas closing a non-idle pooled connection should abruptly close it.
I would propose that there would by just a single (volatile) field inside NpgsqlConnector that would indicate if connector actions should be cancelled because connector is closing. This field would be checked by a method (CheckClosingState) that would throw an internal exception e.g. ConnectorClosingException if closing/cancelling is indicated. This method would be called inside relevant methods e.g. in PerformKeepAlive-SkipUntil and the possible ConnectorClosingException would be properly handled so that the operation is gracefully cancelled.
Using this mechanism the Close/Break would first set this closing state field and after this wait for the semaphore to be released. This waiting should be short since the currently running operation e.g. keep alive would be cancelled almost immediately. After the semaphore has been released all the resources are disposed. This would still need some little extra to make sure that the keep alive timer thread would not fire up and use the disposing resources while Close is running.
It's an interesting idea but I'm not sure it's really necessary - and it has the downside of littering lots of codepaths with checks everywhere (and we need to remember them as new codepaths are added).
I see things in a simpler way. Close should simply attempt to acquire both the user lock and the keepalive lock. If it succeeded, that means the connection is totally idle and can be closed gracefully (with a Terminate message). Note that as long as both locks are held by the close process, no user action or keepalive can start.
If close fails to acquire any of these locks because it's already taken, we switch to the abrupt close instead. Abrupt close should close the socket and immediately set any ongoing operation to disposed state. In other words, if there's an open NpgsqlDataReader, its state should be set to disposed; this way, the next time another thread attempts to interact with the NpgsqlDataReader they will get an ObjectDisposedException, which is the correct behavior. The same needs to happen with ongoing COPY operations.
The advantage is that normal codepaths don't need to check anything beyond regular "is disposed" checks which are already there.
Note that as I wrote above, if a keepalive is in progress when close is called, it makes sense to give it a few seconds to complete before switching to abrupt closing. This would prevent some spurious abrupt closing - although if a keepalive hasn't completed after a few seconds we should do this anyway.
If you guys see any holes with this idea I'd be interested to hear about it.
Aside from keepalives, everything that happens in Npgsql is user-initiated: the user starts a query and reads the results, etc. So I agree with what you're saying, with one exception: closing an idle connection should first send the PostgreSQL Terminate message. This lets PostgreSQL know about the connection (rather than an abrupt socket close), which is a good thing - otherwise PostgreSQL emits an error in its logs. So I see close as having two paths, a bit how you first described things: if the connection is idle Terminate is sent, otherwise the socket is abruptly closed. Also we need to remember pooling: closing an idle pooled connection needs to return it to the pool, whereas closing a non-idle pooled connection should abruptly close it.
With the Terminate message process being time limited, and robust against losing the connection in case it was lost during the transmission of the terminate message or receiving its acknowledgement.
And Close itself must be safe against re-entry, ie: If Close is called again while it is waiting, it should block the other caller till it is done. (and Open the same thing, both sync and async versions).
Note that as I wrote above, it makes sense if a keepalive is in progress when close is called, it makes sense to give it a few seconds to complete before switching to abrupt closing. This would prevent some spurious abrupt closing - although if a keepalive hasn't completed after a few seconds we should do this anyway.
Take care of there of the case where you are in Close waiting for keepalive, and keepalive suddenly loses the socket or blows up. (ie: internal conversion of graceful shutdown to abrupt shutdown).
The advantage is that normal codepaths don't need to check anything beyond regular "is disposed" checks which are already there.
I don't like the idea of reusing the dispose checks because in case an idle connection (or even in use), spontaneously blows up, the keep alive thread is the one that blew up, the class will start behaving as if it had been spontaneously disposed.
I think it would be very confusing for a class to dispose itself, so there has to be a "broken" state in which the class is non-functional but not-disposed, and the methods should behave accordingly (checking 2 states, broken or disposed). Then something should react and call Dispose on the connection from outside it.
With the Terminate message process being time limited, and robust against losing the connection in case it was lost during the transmission of the terminate message or receiving its acknowledgement.
Yes.
And Close itself must be safe against re-entry, ie: If Close is called again while it is waiting, it should block the other caller till it is done. (and Open the same thing, both sync and async versions).
I don't know about Close being reentrant - why would be the use case for supporting this? We should probably not bomb in a very ugly way, but actually support reentrant close where the second call blocks - I don't see the purpose...
Take care of there of the case where you are in Close waiting for keepalive, and keepalive suddenly loses the socket or blows up. (ie: internal conversion of graceful shutdown to abrupt shutdown).
Yes, that's right. This kind of check already happens when a user action is waiting for a keepalive to complete, and the makes sure the connection is still alive. Basically all checks on the state to the connection should only happen after both locks have been acquired.
I don't like the idea of reusing the dispose checks because in case an idle connection (or even in use), spontaneously blows up, the keep alive thread is the one that blew up, the class will start behaving as if it had been spontaneously disposed.
I think it would be very confusing for a class to dispose itself, so there has to be a "broken" state in which the class is non-functional but not-disposed, and the methods should behave accordingly (checking 2 states, broken or disposed). Then something should react and call Dispose on the connection from outside it.
I think you're confusing the connection with the reader (or copy operation) - these are different things.
NpgsqlConnection has a standard ADO.NET State property which can tell you whether a connection is open or closed. It also provides a non-standard FullState property which provides more detail, specifically the distinction between Closed and Broken. Where a non-recoverable error happens in Npgsql (e.g. timeout), the Break() internal method is called and the connection is set to state Broken. This is the way things already work. Close should always put the connection in state Closed, even if an abrupt close occurred (because the connection was busy).
But in addition to the connection there are objects representing ongoing operation, e.g. NpgsqlDataReader represents an executing query. If an abrupt close occurs, an open NpgsqlDataReader should be immediately disposed, so that users can't continue using it. By the way, this is exactly how SqlClient behaves - closing while a reader is open implicitly disposes the reader.
Ah, ok, if the convention is for the DataReader object to have the possibility of becoming spontaneously disposed while being used in case of an error in the connection, then it should be fine, I think.
Activity
[-]Design ideas for proper thread-safe shutdown procedure for 3.2[/-][+]Design ideas for proper thread-safe shutdown procedure[/+]roji commentedon Jun 14, 2016
Hi @rwasef1830, I assume this is a proposal for properly resolving #1151 (and the other close-related sync issues detailed there). Thanks for your detailed thoughts on this! @MarkusSintonen, you may find this discussion interesting.
First, in case you're not aware Npgsql already manages 2 SemaphoreSlims, one for user actions and one for keepalives. When a user action starts (e.g. ExecuteReader), the user action semaphore is taken (an "Operation is already in progress" is thrown if the semaphore is already taken), and then the keepalive semaphore is busy. This makes sure we don't start a user action while a keepalive is in progress. All operations using the connection are supposed to go through this mechanism, ensuring that operations never run concurrently and that users get clean exceptions (as opposed to undefined behavior).
One current problem is that open and close do not take these semaphores, which is why @MarkusSintonen ran into a race condition if close happens just as a keepalive is in progress. This is tracked by #1127. My current direction to fix this in 3.2 is simply to make sure the semaphores are properly taken in close and open. Close is a bit tricky though: if a user operation or keepalive is in progress while Close is called, we want an abrupt shutdown (this isn't the behavior in 3.1, which instead waits for the operation to complete). However, making this work doesn't seem too hard - it's just too big a change for a patch-level 3.1 release.
Now regarding some of your specific comments:
I assume you're proposing to use the cancellation tokens just as a way to trigger the cancellation code, right? I mean, all this logic has to happen for synchronous operations which don't support cancellation tokens directly in any way... In that case, I'm not sure I see the usefulness of cancellation tokens vs. simply directly calling methods that perform the shutdown logic. Note that NpgsqlConnector already has a method Break() which is called whenever the connection is no longer usable (e.g. timeout). This method is very similar to your concept of an abrupt shutdown.
To be honest, if the user requests a Close while one of their operations is still in progress, I don't even think we should wait for the operation to end on its own (graceful shutdown). In other words if an operation is in progress, it seems to me that a Close should be abrupt. The user is in control and chooses when to Close, and they can also decide to implement a timeout themselves if they so desire. Note that if a keepalive is in progress it does make sense to wait a bit, since keepalives aren't a user-triggered operation and are typically very short too.
Yep, I agree as I said above. The semaphore (or rather the two semaphores) already exist and are used, just not for open and close.
This is already the case, it happens when the Break() method is called.
Thanks for offering to help with this, but it would be better to fully lock the design down in discussion before starting work. Note that I also have some WIP on this in a branch.
rwasef1830 commentedon Jun 14, 2016
Hey @roji,
Hmmm, my model was based on a design I used for a completely async bidirectional packet-based binary protocol. I guess I didn't properly consider sync operations. I have to admit I am not familiar with the internal design of the NpgsqlConnection :-). I was just throwing out ideas to raise some insights.
The structure I proposed would be internal, not exposed to the users. It would be used for coordinating the internal components and dependencies of the connection itself, not passed from outside by the user. I favored basing it on
CancellationTokenbecause internally it handles the tricky lock-free multi-threading / read/write-fencing stuff so I don't have to worry about it.In addition, it can be exposed to consumers of the connection (if there were any events or callbacks) to give them a chance to participate in the coordinated shutdown and it can be passed to any "injected" dependencies of the connection to link them easily into the shutdown process without strong coupling to the core connection code. (see
HttpContext.RequestAbortedfor a similar idea used in ASP.net Core RC2).If there are no possible background received commands or notifications from Postgresql, then
Closeshould just immediately close the Socket and background tasks should be robust against that possibility, logging if this happened unexpectedly, or suppressing the warnings if the loss was due to the user callingClose.I have to admit that I'm not really familiar with all features of Postgresql :-), learning as I go.
Well, I hope my idea helps in any way or leads to a more robust implementation. I struggled on such a task for weeks a few months ago :-).
MarkusSintonen commentedon Jun 14, 2016
Hi @roji and @rwasef1830,
I also think that the design using CancellationTokens is too heavy weight solution here since the NpgsqlConnector is fairly synchronous in nature (except that keep alive).
I would propose that there would by just a single (volatile) field inside NpgsqlConnector that would indicate if connector actions should be cancelled because connector is closing. This field would be checked by a method (CheckClosingState) that would throw an internal exception e.g. ConnectorClosingException if closing/cancelling is indicated. This method would be called inside relevant methods e.g. in PerformKeepAlive-SkipUntil and the possible ConnectorClosingException would be properly handled so that the operation is gracefully cancelled.
Using this mechanism the Close/Break would first set this closing state field and after this wait for the semaphore to be released. This waiting should be short since the currently running operation e.g. keep alive would be cancelled almost immediately. After the semaphore has been released all the resources are disposed. This would still need some little extra to make sure that the keep alive timer thread would not fire up and use the disposing resources while Close is running.
roji commentedon Jun 14, 2016
@MarkusSintonen no problem, your thoughts are definitely relevant!
Well, NpgsqlConnection already has the ADO.NET standard StateChange event which gets fired when the connection state changes, i.e. on open/close. This is the standard way to get updates on what's happening with the connection in a weakly-coupled way.
Aside from keepalives, everything that happens in Npgsql is user-initiated: the user starts a query and reads the results, etc. So I agree with what you're saying, with one exception: closing an idle connection should first send the PostgreSQL Terminate message. This lets PostgreSQL know about the connection (rather than an abrupt socket close), which is a good thing - otherwise PostgreSQL emits an error in its logs. So I see close as having two paths, a bit how you first described things: if the connection is idle Terminate is sent, otherwise the socket is abruptly closed. Also we need to remember pooling: closing an idle pooled connection needs to return it to the pool, whereas closing a non-idle pooled connection should abruptly close it.
@MarkusSintonen,
It's an interesting idea but I'm not sure it's really necessary - and it has the downside of littering lots of codepaths with checks everywhere (and we need to remember them as new codepaths are added).
I see things in a simpler way. Close should simply attempt to acquire both the user lock and the keepalive lock. If it succeeded, that means the connection is totally idle and can be closed gracefully (with a Terminate message). Note that as long as both locks are held by the close process, no user action or keepalive can start.
If close fails to acquire any of these locks because it's already taken, we switch to the abrupt close instead. Abrupt close should close the socket and immediately set any ongoing operation to disposed state. In other words, if there's an open NpgsqlDataReader, its state should be set to disposed; this way, the next time another thread attempts to interact with the NpgsqlDataReader they will get an ObjectDisposedException, which is the correct behavior. The same needs to happen with ongoing COPY operations.
The advantage is that normal codepaths don't need to check anything beyond regular "is disposed" checks which are already there.
Note that as I wrote above, if a keepalive is in progress when close is called, it makes sense to give it a few seconds to complete before switching to abrupt closing. This would prevent some spurious abrupt closing - although if a keepalive hasn't completed after a few seconds we should do this anyway.
If you guys see any holes with this idea I'd be interested to hear about it.
rwasef1830 commentedon Jun 14, 2016
@roji @MarkusSintonen
With the Terminate message process being time limited, and robust against losing the connection in case it was lost during the transmission of the terminate message or receiving its acknowledgement.
And Close itself must be safe against re-entry, ie: If Close is called again while it is waiting, it should block the other caller till it is done. (and Open the same thing, both sync and async versions).
Take care of there of the case where you are in Close waiting for keepalive, and keepalive suddenly loses the socket or blows up. (ie: internal conversion of graceful shutdown to abrupt shutdown).
I don't like the idea of reusing the dispose checks because in case an idle connection (or even in use), spontaneously blows up, the keep alive thread is the one that blew up, the class will start behaving as if it had been spontaneously disposed.
I think it would be very confusing for a class to dispose itself, so there has to be a "broken" state in which the class is non-functional but not-disposed, and the methods should behave accordingly (checking 2 states, broken or disposed). Then something should react and call Dispose on the connection from outside it.
What do you think ?
roji commentedon Jun 14, 2016
Yes.
I don't know about Close being reentrant - why would be the use case for supporting this? We should probably not bomb in a very ugly way, but actually support reentrant close where the second call blocks - I don't see the purpose...
Yes, that's right. This kind of check already happens when a user action is waiting for a keepalive to complete, and the makes sure the connection is still alive. Basically all checks on the state to the connection should only happen after both locks have been acquired.
I think you're confusing the connection with the reader (or copy operation) - these are different things.
NpgsqlConnection has a standard ADO.NET
Stateproperty which can tell you whether a connection is open or closed. It also provides a non-standardFullStateproperty which provides more detail, specifically the distinction between Closed and Broken. Where a non-recoverable error happens in Npgsql (e.g. timeout), the Break() internal method is called and the connection is set to state Broken. This is the way things already work. Close should always put the connection in state Closed, even if an abrupt close occurred (because the connection was busy).But in addition to the connection there are objects representing ongoing operation, e.g. NpgsqlDataReader represents an executing query. If an abrupt close occurs, an open NpgsqlDataReader should be immediately disposed, so that users can't continue using it. By the way, this is exactly how SqlClient behaves - closing while a reader is open implicitly disposes the reader.
rwasef1830 commentedon Jun 14, 2016
Ah, ok, if the convention is for the DataReader object to have the possibility of becoming spontaneously disposed while being used in case of an error in the connection, then it should be fine, I think.
roji commentedon Sep 17, 2020
A bit less important now that async cancellation will be implemented.