Skip to content

[WIP] Fix | Trying to fix the issue with SqlBulkcopy Async pattern -draft design - #783

Closed
JRahnama wants to merge 1 commit into
dotnet:mainfrom
JRahnama:SqlBulkCopyAsync
Closed

JRahnama wants to merge 1 commit into
dotnet:mainfrom
JRahnama:SqlBulkCopyAsync

Conversation

@JRahnama

@JRahnama JRahnama commented Nov 4, 2020 •

Copy link
Copy Markdown
Contributor

Related Issue(s): Issue #716

This is a draft pull request and still has room to improve.

Current Design

Async and sync calls in SqlBulkcopy are distinguished by two factors in Current design:

  1. By a boolean variable, _isAsyncBulkCopy, which could be set to true or false based on the call from the user.
    For example, if user calls WriteToServer(IDataReader reader), this will set the mentioned variable to false, sets the statistics and calls WriteRowSourceToServerAsync(reader.FieldCount, CancellationToken.None).
    When user calls WriteToServerAsync(DbDataReader reader), this will call an overload of the same function with Cancelation token added to it and from there it calls the same function as sync call, WriteRowSourceToServerAsync.

  2. From here the only difference between sync and async calls are based on return value of each task. If a return value of a task is null, that implies that sync pattern is called and if it returns a a task that means an async call is in progress.

Note
Same pattern has been used in different places of the M.D.S. For example reconnect task in SqlConnection follows the same pattern.


What has been done so far

  1. SqlBulkCopy is separated to two partial classes, SqlBulkCopy and SqlBulkCopy.Async, in a new folder called BulkCopy. I have been planning to do this for a long time and I found a good occasion. All SqlBulkCopy related is moved to this folder.
  2. All related Async functions are moved to SqlBulkcopy.Async
  3. The _isAsyncBulkCopy is removed as it is not needed any more.
  4. Async/await pattern does not accept out/reference/in values. changed them accordingly.
  5. I have tried to remove TaskCompletionSource as much as possible in async/await pattern, but not much luck. Needs more thinking and time. I may move back to this after GA.
  6. I have removed the if/else validation for task result. The one validates if an actual task is returned (async) or it is null (sync).
  7. Changed the new design to use async/await pattern, which is not completed yet. (We probably need to redesign SqlBulkCopy.Async).

@JRahnama JRahnama linked an issue Nov 4, 2020 that may be closed by this pull request
@JRahnama JRahnama changed the title Fix | trying to fix the issue with SqlBulkcopy Async pattern -draft design Fix | Trying to fix the issue with SqlBulkcopy Async pattern -draft design Nov 4, 2020
@Wraith2

Wraith2 commented Nov 4, 2020

Copy link
Copy Markdown
Contributor

Is there a particular goal for this set of changes other than making the code easier to work with?

It's worth noting that while going to language based async makes the code a lot easier to work with it can have detrimental performance characteristics if you're capturing a lot of state. C#9 static lambdas would help with that if we could bump the langauge version.

@roji

roji commented Nov 4, 2020

Copy link
Copy Markdown
Member

It's worth noting that while going to language based async makes the code a lot easier to work with it can have detrimental performance characteristics if you're capturing a lot of state.

That certainly used to be true, and one must still be careful with what gets capture with async/await. However, nowadays async/await is generally optimized and can be considerably more efficient than more traditional callback-based approaches. I benchmarked async/await vs. ContinueWith a while ago and the former was considerably faster.

It's always good to work with benchmarks when doing this kind of code change, but I'd say that any change from traditional callback-based async programming to async/await is in principle a positive direction :)

@JRahnama

JRahnama commented Nov 4, 2020

Copy link
Copy Markdown
Contributor Author

Is there a particular goal for this set of changes other than making the code easier to work with?

I believe this could be the first step of changing Async pattern in the driver. Nothing could/would be changed drastically, without designing the core of the driver for async pattern, what we need is RunAsync in TdsParser. Separating sync and Async will give us the opportunity to work solely on Async part without touching the fine working sync part. If there is any plan to re-design the code this change makes it easier and less harmful. Even with the current pattern, SqlBulkCopy.Async could be re-designed to perform better. I can address/direct you to one of the parts that makes async slower in this design. CopyRowsAsync method! the entire for loop is designed for sync pattern and it works perfect there, but it always exits the loop with the first try/run in async and the entire process starts from the beginning..... if you take the null part of the task out, VS will show unreachable code for variable i++ ........

It's worth noting that while going to language based async makes the code a lot easier to work with it can have detrimental performance characteristics if you're capturing a lot of state. C#9 static lambdas would help with that if we could bump the langauge version.

I agree, but we cannot jump to C#9 while we are supporting netcore 3.1 and netfx 4.6. In near future, support for .NET 5 will be added to the driver and in my personal opinion that is where we will need all this changes to happen.

public partial class SqlBulkCopy
{
// Newly added member variables for Async modification, m = member variable to bcp.
private int _savedBatchSize = 0; // Save the batchsize so that changes are not affected unexpectedly.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor point. Initialization to default values for types other than span is generally unnecessary because of runtime guarantees. Doing so causes the code to be emitted in the ctor and while it isn't a big cost it isn't one that is needed either.

Task reconnectTask;
try
{
reconnectTask = _connection.ValidateAndReconnect(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

async capture, is it possible to pass the parserLock as a state parameter?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have not spend much time in reconnect task in SqlConnection. It follows the same steps, if the task returns null/task. I am not sure if AsyncHelper could be called to pass state on it. I will look into that tomorrow. In my opinion AsyncHelper is one the parts that we need to remove or at least simplify it with Task's built-in capabilities.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally AsyncHelper wouldn't be needed at all, i agree. Since it is currently needed and I've spent time around it this one stuck out to me while i was reviewing the code. If you'd prefer not to change this then I'm ok with that.

Comment on lines +58 to +65
_rowStateToSkip = DataRowState.Deleted; // Don't allow deleted rows
_rowSource = rows;
_dataTableSource = table;
_SqlDataReaderRowSource = null;
_rowSourceType = ValueSourceType.RowArray;
_rowEnumerator = rows.GetEnumerator();
_isAsyncBulkCopy = true;
resultTask = WriteRowSourceToServerAsync(table.Columns.Count, cancellationToken); // It returns Task since _isAsyncBulkCopy = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block and most of the method feels a bit boiler-plate. Do some checks, setup statistics, then do the variable bit and then cleanup. Is it worth abstracting it out as a separate method do you think?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. I will look into that tomorrow.

@Wraith2

Wraith2 commented Nov 5, 2020

Copy link
Copy Markdown
Contributor

I believe this could be the first step of changing Async pattern in the driver. Nothing could/would be changed drastically, without designing the core of the driver for async pattern, what we need is RunAsync in TdsParser. Separating sync and Async will give us the opportunity to work solely on Async part without touching the fine working sync part

I really like the idea but have found that this can lead to multiple implementations all the way down and I'm not sure having two implementations of Run is good for maintenance. @roji probably has some good guidance here from the postgres driver, do you end up parallel or have a single implementation that both worlds use? and if so is it sync or async?

it always exits the loop with the first try/run in async and the entire process starts from the beginning..... if you take the null part of the task out, VS will show unreachable code for variable i++ ........

Yes I've seen that pattern. Parts of SqlCommand do the same and it's part of the cause of the string perf issues we've noted in the past. Essentially it tries fails and then tries again from the beginning. Easier on state management and simpler from an initial implementation perspective (because you always have full state to debug) but sort of sulky for perf.

I have ideas on how to address it in a general way but I was trying to merge as much of the codebases from netfx and netcore before I started on major internal reworks. Run and all the methods above and below it in the parser should be changed to return OperationStatus instead of bool, with that done you can now identify the cause of a parse failure and possibly suspend state cleanly for a resumption on the next async packet.

I agree, but we cannot jump to C#9 while we are supporting netcore 3.1 and netfx 4.6. In near future, support for .NET 5 will be added to the driver and in my personal opinion that is where we will need all this changes to happen.

Well... you sort of can. It's not a supported scenario but it is a working scenario. 😁 I checked with the langauge team on discord and as long we we don't use any language features that require library or runtime support it'll still work on downlevel frameworks. I understand your point though and the example of static lambdas to prevent accidental closure allocations is unlikely to be worth it, it would emit correct il working though.

@roji

roji commented Nov 5, 2020

Copy link
Copy Markdown
Member

I really like the idea but have found that this can lead to multiple implementations all the way down and I'm not sure having two implementations of Run is good for maintenance. @roji probably has some good guidance here from the postgres driver, do you end up parallel or have a single implementation that both worlds use? and if so is it sync or async?

I don't know the internals at all, but doesn't SqlClient already have separate implementations for sync and async? If so, then at minimum, rewriting the callback-based async implementation to use async/await wouldn't be making the situation worse...

More in detail... Npgsql does have a unified code path for sync and async for almost all the logic. This mean that you typically have a single method which accepts an async flag and returns Task/ValueTask. The flag determines whether, if and when I/O occurs, it will be done via sync or async; in other words, at the very bottom of the stack, at some point you have a condition on the flag, and call Read or ReadAsync. Intermediate methods - those not performing I/O themselves but only calling other methods - simply pass this flag down and don't have to care about it. This all means we don't have duplicate code paths to maintain - everything goes through the same methods.

Now, if all your methods have the async keyword on them, that means that for user sync APIs, you're potentially paying the overhead of the compiler-generated async state machine although it's not needed (since the method will never actually do any async operations. In fact, even for user async APIs, many calls won't necessarily need to do any I/O - the driver buffers internally, and so calls like DbDataReader.Read won't need to do any I/O (because the next row is already in memory).

The overhead of async state machines has been greatly optimized in recent versions of .NET Core. However, for true pedal-to-the-metal perf, it's possible to provide a fast-path sync implementation which only calls into an async one when necessary:

public ValueTask<SomeData> GetData(bool async, CancellationToken cancellationToken = default)
{
    return dataAlreadyInMemory
        ? theData
        : GetDataAsync();

    async ValueTask<SomeData> GetDataAsync(bool async CancellationToken cancellationToken = default)
    {
        // Perform actual I/O and return the data
    }    
}

With this kind of trick, you avoid going through state machines as long as data is already buffered; and if you have to do I/O, then the state machine overhead is likely negligible anyway. It's also sometimes worth merging two async methods into one, again to cut down on the number of async state machines you have in your stack - the overhead does add up.

But I'd recommend not going into this kind of optimization right away - that can always happen later. My personal recommendation in terms of next steps would be something like:

  • Incrementally convert callback-based async code to async/await based code. This will likely not regress perf (though always measure), would probably make the code much saner and expose/fix quite a few bugs.
  • Optionally look into merging sync and async paths - since after conversion to async/await the sync and async paths should look quite similar.
  • Look into optimizing the code with fast-paths to avoid state machine overhead, and cutting down on the number of async state machines.

Hope this helps... Am definitely available for any further questions/discussions on this.

Well... you sort of can. It's not a supported scenario but it is a working scenario

You're right here - static lambdas (and some other C# 9 features) are compiler-only features which should always work. Other features (e.g. covariant return types) require the new runtime and therefore will not work. Static lambdas are generally a good idea to reduce allocations - I agree that SqlClient is probably facing more important perf problems, but it sure wouldn't hurt to use static lambdas when writing new code.

@JRahnama
JRahnama marked this pull request as draft November 5, 2020 19:38
@Wraith2

Wraith2 commented Nov 6, 2020

Copy link
Copy Markdown
Contributor

There is some interesting code that handles sync and async callers in sync mode using api-async. An example of this is TdsParserStateObject.WriteBytes , it's fairly central to low level operations of writing bytes to the packets. Have a glance at the code. It's a fully sync method that signals whether it's working in async mode by returning a task to callers, if it returns a task that usually gets passed up the stack so whoever is doing the language async part gets to wait on it. The library itself does not await anything that I've ever seen it just sets up tasks and continuations.

The problem I have with it is that because of all the looping and conditionals that exist here and levels above it it takes a lot of mental space to make sure your handle all routes through the code cleanly. I don't know if others have the same experience but I'd like to have some of the more important code in the library be significantly more straightforward to understand.

There's a big Run method in the parser which is the main state machine implementation for incoming packets. State switches get long quickly and there are lots of quirks to account for because of old protocol versions and bug fixes. I'd prefer not to have two large state driver methods but having one which works in both sync and async modes either means a lot of conditionals on async or a completely separating io from parser driving and making all state transitions completely resumable which is complicated.

@roji

roji commented Nov 7, 2020

Copy link
Copy Markdown
Member

@Wraith2 I very much agree with everything you say, and I'd say that the various async-related issues found in SqlClient are a good additional argument to try to make things saner by incrementally doing async/await (if possible). Callback-based async (like the WriteBytes method you linked to) is notoriously hard to follow and grasp, is inherently bug-prone, and those are the very reasons why async/await was invented - it allows writing and reasoning about async code in almost the same way as simple sync code.

BTW the WriteBytes method you linked to is odd, in that it both returns a Task and accepts a TaskCompletionSource as a continuation (which, by the way means a lot of allocations as TCS cannot be recycled). I'd expect it to do either one or the either, but not both.

@JRahnama

JRahnama commented Nov 9, 2020

Copy link
Copy Markdown
Contributor Author

@Wraith2 , @roji Thanks for all the efforts. We are currently busy with the GA activities. The moment we are done with it I'll come back to this PR and go through all the comments and recommendations. I really appreciate all the support.

{
SqlStatistics.StopTimer(statistics);
}
await Task.WhenAll(resultTask);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why await here?

private SqlInternalConnectionTds.SyncAsyncLock _parserLock = null;

/// <include file='../../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml' path='docs/members[@name="SqlBulkCopy"]/WriteToServerAsync[@name="DataRowParameter"]/*'/>
public async Task WriteToServerAsync(DataRow[] rows) => await WriteToServerAsync(rows, CancellationToken.None);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we awaiting these methods?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated comment: it is possible to remove the async and await keywords here, and just return the Task directly. This removes an async state machine and helps performance.

This trick can be done anywhere where the await call is the last line in a method.

@cheenamalhotra cheenamalhotra changed the title Fix | Trying to fix the issue with SqlBulkcopy Async pattern -draft design [WIP] Fix | Trying to fix the issue with SqlBulkcopy Async pattern -draft design Feb 23, 2021
Base automatically changed from master to main March 15, 2021 17:54
@JRahnama JRahnama closed this Jul 6, 2021
@JRahnama
JRahnama deleted the SqlBulkCopyAsync branch July 6, 2021 19:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Poorer performance using BulkCopy.WriteToServerAsync vs WriteToServer

4 participants