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
Multi-statement commands with dependencies are broken #641
I got another issue with the new 3.0 version (changeset 9a89800).
I have a sql text which creates a function and then executes it. Npgsql throws a NpgsqlException
which contains a "function does not exist" message. The function was not created. If i remove the
function call then the function gets created.
here is the code for a test which throws the exception with the current version:
[Test]publicvoidCreateAndExecuteFunction(){conststringquery=@"CREATE FUNCTION pg_temp.createandexecute() RETURNS boolean AS $BODY$DECLAREBEGIN RETURN TRUE;END;$BODY$ LANGUAGE 'plpgsql';SELECT pg_temp.createandexecute();";objectresult=ExecuteScalar(query);Assert.AreEqual(true,result);}
Confirmed. if the function creation is split into a different command then everything is fine.
Unfortunately this seems to be a result of Npgsql's switching to using the PostgreSQL extended protocol, rather than the previously-used simple protocol. The same thing occurs when creating a table and selecting from it in the same command. I'm not sure why the extended protocol makes this impossible.
I've updated our in-progress 3.0 migration guide to let people know about this.
For anyone wondering about the switch to extended, it allows us to do things like parameters in multiple-query commands, binary encoding, etc.
The issue is specifically since our extended query implementation sends Parse1/Describe1/Bind1/Parse2/Describe2/Bind2/Execute1/Close1/Execute2/Close2/Sync. In other words the second command's Parse is sent before the first command's Execute...
@Emill, do you recall exactly why we decided to order the messages this way, and not simply P1/D1/B1/E1/C1/P2/D2/B2/E2/C2/S?
Yes, it's to make sure everything is buffered up at the backend before executing starts. Otherwise deadlock might happen if you send two large queries and the first resultset returns a lot of data, We try to send everything at once, but the backend tries to send the first whole response before reading the next query.
Do you see any way out of this? I don't... it doesn't seem like an extremely important issue - I'm OK with documenting it and leaving it - but it would be nice if we could solve it somehow.
Yes, I did: see here and associated thread messages.
It actually makes total sense to me - it's simply because we send the second query's Parse before sending the first query's Execute (in order to avoid the deadlock).
Here's an implementation idea that solves both problems... We switch back to sending P/D/B/E, but we:
Pack all messages that would fit into a single buffer/packet.
If those messages didn't contain an Execute (e.g. very long Parse), we do the same thing until we've sent an Execute
We switch control to the user, who now uses the reader to process messages.
When NextResult() is called, we check if we're expecting more results for another query we've already sent. If so, we continue reading just like now.
If the reader has processed the results for all the queries already sent, we jump back to step 1 and send more queries.
Advantages:
We switch to the better P/D/B/E mode, solving this issue.
P/D/B/E also seems better in that it uses the anonymous statement and the the anonymous portal (we currently use named portals). This is supposed to be a bit better on the PostgreSQL side I think.
It solves the other (exotic) deadlock situation where we don't read ParseComplete and BindComplete messages as we're sending queries (this is why we currently have a "maximum queries in multiquery" upper limit).
It also doesn't penalize performance by sending queries one by one - small queries get packed into a single packet just like now.
There is a small performance penalty because instead of sending all messages upfront right away, there's a delay between us receiving the end of the resultsets and having to send the next query (or queries).
What do you think? The implementation is a bit more complicated but it seems to solve everything in an elegant way?
Just to improve/clarify the idea above: we could use non-blocking sockets for writing. The moment a write would block, we transfer control to the user who reads data. When the user went through all the data, the next NextResult continues sending more queries.
The only problem seems to be async, since non-blocking doesn't affect async. I'm still looking for a solution for that...
That might be an idea. But just because it blocks doesn't necessarily mean it will block forever (until we read back the response and the backend continues reading). It might just mean a network transfer is going on and there is not room in the send buffer at the moment. The optimum solution would be to stop when the tcp layer indicates the backend has a zero receive window but I don't think .NET exposes that...
That's a good point. I'm not even sure this kind of info is exposed in C (and that's before talking about cross-platform)... On the upside, don't forget we would still be writing 8K buffer chunks, so even if we do lose a bit of performance (by transferring control to the user too eagerly) it doesn't seem so bad.
One more important point is that we would be using non-blocking writes only once we've written at least one Execute message - we can use normal blocking I/O as long as we're still in the middle of the first query. This is because we can't transfer control to the user before sending at least one Execute (no data is coming yet). That would also limit the performance problem you mentioned.
I'm more worried about what to do with async operations.
Actually, thinking about it some more, async doesn't seem to be an issue. We should use regular WriteAsync to write the first query (up to and including the first Execute). Then, we should use nonblocking Write, exactly like with sync operations - it's OK to use it within async flow since we know it will never block. Either it writes messages immediately without blocking, or it returns immediately and we transfer control to the user.
@Emill, I think I'll make this change, even if it's a bit big and it's a bit late for 3.0. Let me know if you see an issue, and it would be great to get your review when I'm done...
The problem with non-blocking writes is that the stream API itself doesn't support it... In C, write() returns the number of bytes written (and in non-blocking this is less than the attempted bytes). However, in .NET Stream.Write() returns void for some reason...! This is why I was thinking of dropping the stream API altogether and simply write byte arrays. I think this makes a lot of sense in Npgsql - we already carefully fill in a byte buffer and manage things in a packet-oriented way, for efficiency reasons, streams don't give us that much.
Another thing is that this could maybe allow us to go back to using SSLStream rather than our own implementation (but that's a different conversation).
Another thing is that this could maybe allow us to go back to using
SSLStream rather than our own implementation (but that's a different conversation).
I don't think SslStream supports non-blocking sockets. Or what where you thinking about?
@Emill you're right, since SSLStream is a Stream it doesn't support non-blocking writes. So my idea is to use SSLStream over a MemoryStream in order to write into a buffer, which will therefore contain encrypted data, which we will then send via non-streaming (i.e. packet-oriented) methods. So we use SSLStream to encrypt a clear-text buffer (which we already populated with PostgreSQL messages) into a crypt-buffer, but handle the actual sending ourselves... Does that make sense?
@byrney yes, parameter binding will continue to happen at the server side as before, with Npgsql sending all parameters as usual with the Bind message. Nothing changes in that respect.
Regardless, all PostgreSQL messages have a signed Int32 for the length, which I think means the entire Bind method is limited to 2GB, so nearly 2GB for all parameters combined, for a given statement.
Hahaha using SslStream over some memory stream was clever. I should never have thought of that. Keep in mind that it will generate extra packets apart from the application data when renegotiations occur.
FYI I've just pushed a branch that solves this issue via another approach. Rather than doing non-blocking writes, which are complicated and especially incompatible with encryption as mentioned above, I've tried something else. The work is visible in this branch, the important commit is "Message writing redo". I would really appreciate comments on the general approach as well as a detailed code review (@Emill?)
The non-prepared message flow is now Parse/Bind/Describe/Execute, which solves the statement dependency issue we have in 3.0 - the second statement can now refer to entities created in the first, etc. To avoid the deadlock issue, any buffer that needs to be sent after the first statement has been sent, is sent asynchronously. In other words, protocol messages for the first statement are sent synchronously as before, but protocol messages for the second statement and beyond may be sent asynchronously. As a result, Npgsql returns control to the user immediately after having sent the first statement (synchronously), and the user can now start reading. The messages for later statements will be sent in the background, whenever possible.
The only real disadvantage I can think of is that this incorporates async operations within the sync flow. In theory this may place some pressure on the thread pool (as a general resource used as part of async operations), and might be less efficient if async isn't well-implemented (this may be the case with mono on Linux, I don't really know).
Note that because writing and reading can now happen simultaneously, connectors now have separate read and write buffers.
@Emill well, since the order is now P/B/D/E parse errors for later statements will now show up only after traversing the results of the earlier statements. But note that for Execute errors (as opposed to Parse errors) this is already the case for 3.0 - let's say you try to do an insert which violates a constraint in a second statement; you will only see the error after processing the results of the first statement. In a way this makes things more "standard" - all errors are now thrown
However, note that with the current (and also the 3.0) implementation, errors don't show up in NextResult, they show up at the first Read() instead - #400 was opened to complain about this for the first query only. This is because NextResult() only gets you to just before the first the first DataRow message (or error), and you have to call Read() to actually process the message. This is the 3.0 behavior and currently also the 3.1 behavior. Thinking about it now, it would be relatively easy to solve this by reading the first DataRow in NextResult and store it as pending for afterwards (there's already a mechanism for this), I've opened #1032 for this.
Going back to your original question though, there's the problem of write errors that occur during the "disconnected" async send method (SendRemaining). In other words, if we're asynchronously sending buffers for later statements and the user is already reading results, and suddenly we get an I/O error in SendRemaining, what should happen? We can't raise the error to the user because the method is async void, and the exception wouldn't go anywhere. However, since a write error indicates that the socket is broken, the next time the user triggers a socket read they will get an I/O error anyway, so we may as well log the write exception and that's it...
FYI @Emill, @damageboy and others, as long as the multistatement-async branch isn't merged I'm a bit blocked from continuing work on other things, it would be great if you guys can find some time ASAP to look and "sign off" at least on the approach - details and bugs can be fixed later after merging. Thanks...
Note to everyone - I've merged multistatement-async into develop because I started doing some additional unrelated work over it. This doesn't mean it's "accepted" or has no bugs - I'd still appreciate a serious review of 34f80e7 and any general remarks about the approach.
Otherwise, assuming this is OK, it's really good to finally have this issue fixed.
Activity
roji commentedon Jun 11, 2015
Thanks for reporting @Yarith.
Confirmed. if the function creation is split into a different command then everything is fine.
Unfortunately this seems to be a result of Npgsql's switching to using the PostgreSQL extended protocol, rather than the previously-used simple protocol. The same thing occurs when creating a table and selecting from it in the same command. I'm not sure why the extended protocol makes this impossible.
I've updated our in-progress 3.0 migration guide to let people know about this.
For anyone wondering about the switch to extended, it allows us to do things like parameters in multiple-query commands, binary encoding, etc.
roji commentedon Jun 11, 2015
Note: have sent a message to pgsql-hackers to make sure they're aware of this odd behavior, will post replies.
roji commentedon Jun 11, 2015
The issue is specifically since our extended query implementation sends Parse1/Describe1/Bind1/Parse2/Describe2/Bind2/Execute1/Close1/Execute2/Close2/Sync. In other words the second command's Parse is sent before the first command's Execute...
@Emill, do you recall exactly why we decided to order the messages this way, and not simply P1/D1/B1/E1/C1/P2/D2/B2/E2/C2/S?
Emill commentedon Jun 11, 2015
Yes, it's to make sure everything is buffered up at the backend before executing starts. Otherwise deadlock might happen if you send two large queries and the first resultset returns a lot of data, We try to send everything at once, but the backend tries to send the first whole response before reading the next query.
roji commentedon Jun 11, 2015
Right, I managed to forget already...
Do you see any way out of this? I don't... it doesn't seem like an extremely important issue - I'm OK with documenting it and leaving it - but it would be nice if we could solve it somehow.
Emill commentedon Jun 11, 2015
Did you get any response from the pgsql-hackers list why it's happening?
roji commentedon Jun 11, 2015
Yes, I did: see here and associated thread messages.
It actually makes total sense to me - it's simply because we send the second query's Parse before sending the first query's Execute (in order to avoid the deadlock).
Here's an implementation idea that solves both problems... We switch back to sending P/D/B/E, but we:
NextResult()is called, we check if we're expecting more results for another query we've already sent. If so, we continue reading just like now.Advantages:
What do you think? The implementation is a bit more complicated but it seems to solve everything in an elegant way?
roji commentedon Jun 13, 2015
Just to improve/clarify the idea above: we could use non-blocking sockets for writing. The moment a write would block, we transfer control to the user who reads data. When the user went through all the data, the next
NextResultcontinues sending more queries.The only problem seems to be async, since non-blocking doesn't affect async. I'm still looking for a solution for that...
Emill commentedon Jun 13, 2015
That might be an idea. But just because it blocks doesn't necessarily mean it will block forever (until we read back the response and the backend continues reading). It might just mean a network transfer is going on and there is not room in the send buffer at the moment. The optimum solution would be to stop when the tcp layer indicates the backend has a zero receive window but I don't think .NET exposes that...
roji commentedon Jun 13, 2015
That's a good point. I'm not even sure this kind of info is exposed in C (and that's before talking about cross-platform)... On the upside, don't forget we would still be writing 8K buffer chunks, so even if we do lose a bit of performance (by transferring control to the user too eagerly) it doesn't seem so bad.
One more important point is that we would be using non-blocking writes only once we've written at least one Execute message - we can use normal blocking I/O as long as we're still in the middle of the first query. This is because we can't transfer control to the user before sending at least one Execute (no data is coming yet). That would also limit the performance problem you mentioned.
I'm more worried about what to do with async operations.
roji commentedon Jun 14, 2015
Actually, thinking about it some more, async doesn't seem to be an issue. We should use regular
WriteAsyncto write the first query (up to and including the first Execute). Then, we should use nonblockingWrite, exactly like with sync operations - it's OK to use it within async flow since we know it will never block. Either it writes messages immediately without blocking, or it returns immediately and we transfer control to the user.@Emill, I think I'll make this change, even if it's a bit big and it's a bit late for 3.0. Let me know if you see an issue, and it would be great to get your review when I'm done...
roji commentedon Jun 14, 2015
@Emill, do you see any problem with this nonblocking behavior and TLS? Do you think things will work as expected?
32 remaining items
roji commentedon Apr 4, 2016
The problem with non-blocking writes is that the stream API itself doesn't support it... In C, write() returns the number of bytes written (and in non-blocking this is less than the attempted bytes). However, in .NET Stream.Write() returns void for some reason...! This is why I was thinking of dropping the stream API altogether and simply write byte arrays. I think this makes a lot of sense in Npgsql - we already carefully fill in a byte buffer and manage things in a packet-oriented way, for efficiency reasons, streams don't give us that much.
Another thing is that this could maybe allow us to go back to using SSLStream rather than our own implementation (but that's a different conversation).
byrney commentedon Apr 4, 2016
I think it's great that this is going to get a solution.
I assume that Postgres will continue to do the parameter binding and thus nogsql will need to send all parameters for every leg of the batch?
Will you impose a maximum size for parameters?
Emill commentedon Apr 4, 2016
I don't think SslStream supports non-blocking sockets. Or what where you thinking about?
roji commentedon Apr 5, 2016
@Emill you're right, since SSLStream is a Stream it doesn't support non-blocking writes. So my idea is to use SSLStream over a MemoryStream in order to write into a buffer, which will therefore contain encrypted data, which we will then send via non-streaming (i.e. packet-oriented) methods. So we use SSLStream to encrypt a clear-text buffer (which we already populated with PostgreSQL messages) into a crypt-buffer, but handle the actual sending ourselves... Does that make sense?
roji commentedon Apr 5, 2016
@byrney yes, parameter binding will continue to happen at the server side as before, with Npgsql sending all parameters as usual with the Bind message. Nothing changes in that respect.
Regardless, all PostgreSQL messages have a signed Int32 for the length, which I think means the entire Bind method is limited to 2GB, so nearly 2GB for all parameters combined, for a given statement.
Emill commentedon Apr 5, 2016
Hahaha using SslStream over some memory stream was clever. I should never have thought of that. Keep in mind that it will generate extra packets apart from the application data when renegotiations occur.
roji commentedon Apr 18, 2016
FYI I've just pushed a branch that solves this issue via another approach. Rather than doing non-blocking writes, which are complicated and especially incompatible with encryption as mentioned above, I've tried something else. The work is visible in this branch, the important commit is "Message writing redo". I would really appreciate comments on the general approach as well as a detailed code review (@Emill?)
The non-prepared message flow is now Parse/Bind/Describe/Execute, which solves the statement dependency issue we have in 3.0 - the second statement can now refer to entities created in the first, etc. To avoid the deadlock issue, any buffer that needs to be sent after the first statement has been sent, is sent asynchronously. In other words, protocol messages for the first statement are sent synchronously as before, but protocol messages for the second statement and beyond may be sent asynchronously. As a result, Npgsql returns control to the user immediately after having sent the first statement (synchronously), and the user can now start reading. The messages for later statements will be sent in the background, whenever possible.
The only real disadvantage I can think of is that this incorporates async operations within the sync flow. In theory this may place some pressure on the thread pool (as a general resource used as part of async operations), and might be less efficient if async isn't well-implemented (this may be the case with mono on Linux, I don't really know).
Note that because writing and reading can now happen simultaneously, connectors now have separate read and write buffers.
Emill commentedon Apr 18, 2016
What happens if PostgreSQL reports an error for some query in the middle? Where will that error be thrown? When the user executes NextResult?
roji commentedon Apr 19, 2016
@Emill well, since the order is now P/B/D/E parse errors for later statements will now show up only after traversing the results of the earlier statements. But note that for Execute errors (as opposed to Parse errors) this is already the case for 3.0 - let's say you try to do an insert which violates a constraint in a second statement; you will only see the error after processing the results of the first statement. In a way this makes things more "standard" - all errors are now thrown
However, note that with the current (and also the 3.0) implementation, errors don't show up in NextResult, they show up at the first Read() instead - #400 was opened to complain about this for the first query only. This is because NextResult() only gets you to just before the first the first DataRow message (or error), and you have to call Read() to actually process the message. This is the 3.0 behavior and currently also the 3.1 behavior. Thinking about it now, it would be relatively easy to solve this by reading the first DataRow in NextResult and store it as pending for afterwards (there's already a mechanism for this), I've opened #1032 for this.
Going back to your original question though, there's the problem of write errors that occur during the "disconnected" async send method (SendRemaining). In other words, if we're asynchronously sending buffers for later statements and the user is already reading results, and suddenly we get an I/O error in SendRemaining, what should happen? We can't raise the error to the user because the method is async void, and the exception wouldn't go anywhere. However, since a write error indicates that the socket is broken, the next time the user triggers a socket read they will get an I/O error anyway, so we may as well log the write exception and that's it...
roji commentedon Apr 20, 2016
FYI @Emill, @damageboy and others, as long as the
multistatement-asyncbranch isn't merged I'm a bit blocked from continuing work on other things, it would be great if you guys can find some time ASAP to look and "sign off" at least on the approach - details and bugs can be fixed later after merging. Thanks...[-]Multi-statement commands don't work well[/-][+]Multi-statement commands with dependencies are broken[/+]roji commentedon Apr 21, 2016
Note to everyone - I've merged
multistatement-asyncinto develop because I started doing some additional unrelated work over it. This doesn't mean it's "accepted" or has no bugs - I'd still appreciate a serious review of 34f80e7 and any general remarks about the approach.Otherwise, assuming this is OK, it's really good to finally have this issue fixed.